Merge "get rid of Revision::getText" into Wikidata
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * Representation a title within %MediaWiki.
4 *
5 * See title.txt
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 */
24
25 /**
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
30 *
31 * @internal documentation reviewed 15 Mar 2010
32 */
33 class Title {
34 /** @name Static cache variables */
35 // @{
36 static private $titleCache = array();
37 // @}
38
39 /**
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
43 */
44 const CACHE_MAX = 1000;
45
46 /**
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
49 */
50 const GAID_FOR_UPDATE = 1;
51
52 /**
53 * @name Private member variables
54 * Please use the accessor functions instead.
55 * @private
56 */
57 // @{
58
59 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
60 var $mUrlform = ''; // /< URL-encoded form of the main part
61 var $mDbkeyform = ''; // /< Main part with underscores
62 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
63 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
64 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
65 var $mFragment; // /< Title fragment (i.e. the bit after the #)
66 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
67 var $mLatestID = false; // /< ID of most recent revision
68 var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants
69 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
70 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
71 var $mOldRestrictions = false;
72 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
73 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
74 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
75 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
76 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
77 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
78 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
79 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
80 # Don't change the following default, NS_MAIN is hardcoded in several
81 # places. See bug 696.
82 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
83 # Zero except in {{transclusion}} tags
84 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
85 var $mLength = -1; // /< The page length, 0 for special pages
86 var $mRedirect = null; // /< Is the article at this title a redirect?
87 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
88 var $mHasSubpage; // /< Whether a page has any subpages
89 // @}
90
91
92 /**
93 * Constructor
94 */
95 /*protected*/ function __construct() { }
96
97 /**
98 * Create a new Title from a prefixed DB key
99 *
100 * @param $key String the database key, which has underscores
101 * instead of spaces, possibly including namespace and
102 * interwiki prefixes
103 * @return Title, or NULL on an error
104 */
105 public static function newFromDBkey( $key ) {
106 $t = new Title();
107 $t->mDbkeyform = $key;
108 if ( $t->secureAndSplit() ) {
109 return $t;
110 } else {
111 return null;
112 }
113 }
114
115 /**
116 * Create a new Title from text, such as what one would find in a link. De-
117 * codes any HTML entities in the text.
118 *
119 * @param $text String the link text; spaces, prefixes, and an
120 * initial ':' indicating the main namespace are accepted.
121 * @param $defaultNamespace Int the namespace to use if none is speci-
122 * fied by a prefix. If you want to force a specific namespace even if
123 * $text might begin with a namespace prefix, use makeTitle() or
124 * makeTitleSafe().
125 * @throws MWException
126 * @return Title|null - Title or null on an error.
127 */
128 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
129 if ( is_object( $text ) ) {
130 throw new MWException( 'Title::newFromText given an object' );
131 }
132
133 /**
134 * Wiki pages often contain multiple links to the same page.
135 * Title normalization and parsing can become expensive on
136 * pages with many links, so we can save a little time by
137 * caching them.
138 *
139 * In theory these are value objects and won't get changed...
140 */
141 if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
142 return Title::$titleCache[$text];
143 }
144
145 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
146 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
147
148 $t = new Title();
149 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
150 $t->mDefaultNamespace = $defaultNamespace;
151
152 static $cachedcount = 0 ;
153 if ( $t->secureAndSplit() ) {
154 if ( $defaultNamespace == NS_MAIN ) {
155 if ( $cachedcount >= self::CACHE_MAX ) {
156 # Avoid memory leaks on mass operations...
157 Title::$titleCache = array();
158 $cachedcount = 0;
159 }
160 $cachedcount++;
161 Title::$titleCache[$text] =& $t;
162 }
163 return $t;
164 } else {
165 $ret = null;
166 return $ret;
167 }
168 }
169
170 /**
171 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
172 *
173 * Example of wrong and broken code:
174 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
175 *
176 * Example of right code:
177 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
178 *
179 * Create a new Title from URL-encoded text. Ensures that
180 * the given title's length does not exceed the maximum.
181 *
182 * @param $url String the title, as might be taken from a URL
183 * @return Title the new object, or NULL on an error
184 */
185 public static function newFromURL( $url ) {
186 $t = new Title();
187
188 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
189 # but some URLs used it as a space replacement and they still come
190 # from some external search tools.
191 if ( strpos( self::legalChars(), '+' ) === false ) {
192 $url = str_replace( '+', ' ', $url );
193 }
194
195 $t->mDbkeyform = str_replace( ' ', '_', $url );
196 if ( $t->secureAndSplit() ) {
197 return $t;
198 } else {
199 return null;
200 }
201 }
202
203 /**
204 * Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
205 * Uses $wgContentHandlerUseDB to determine whether to include page_content_model.
206 *
207 * @return array
208 */
209 protected static function getSelectFields() {
210 global $wgContentHandlerUseDB;
211
212 $fields = array(
213 'page_namespace', 'page_title', 'page_id',
214 'page_len', 'page_is_redirect', 'page_latest',
215 );
216
217 if ( $wgContentHandlerUseDB ) {
218 $fields[] = 'page_content_model';
219 }
220
221 return $fields;
222 }
223
224 /**
225 * Create a new Title from an article ID
226 *
227 * @param $id Int the page_id corresponding to the Title to create
228 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
229 * @return Title the new object, or NULL on an error
230 */
231 public static function newFromID( $id, $flags = 0 ) {
232 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
233 $row = $db->selectRow(
234 'page',
235 self::getSelectFields(),
236 array( 'page_id' => $id ),
237 __METHOD__
238 );
239 if ( $row !== false ) {
240 $title = Title::newFromRow( $row );
241 } else {
242 $title = null;
243 }
244 return $title;
245 }
246
247 /**
248 * Make an array of titles from an array of IDs
249 *
250 * @param $ids Array of Int Array of IDs
251 * @return Array of Titles
252 */
253 public static function newFromIDs( $ids ) {
254 if ( !count( $ids ) ) {
255 return array();
256 }
257 $dbr = wfGetDB( DB_SLAVE );
258
259 $res = $dbr->select(
260 'page',
261 self::getSelectFields(),
262 array( 'page_id' => $ids ),
263 __METHOD__
264 );
265
266 $titles = array();
267 foreach ( $res as $row ) {
268 $titles[] = Title::newFromRow( $row );
269 }
270 return $titles;
271 }
272
273 /**
274 * Make a Title object from a DB row
275 *
276 * @param $row Object database row (needs at least page_title,page_namespace)
277 * @return Title corresponding Title
278 */
279 public static function newFromRow( $row ) {
280 $t = self::makeTitle( $row->page_namespace, $row->page_title );
281 $t->loadFromRow( $row );
282 return $t;
283 }
284
285 /**
286 * Load Title object fields from a DB row.
287 * If false is given, the title will be treated as non-existing.
288 *
289 * @param $row Object|bool database row
290 */
291 public function loadFromRow( $row ) {
292 if ( $row ) { // page found
293 if ( isset( $row->page_id ) )
294 $this->mArticleID = (int)$row->page_id;
295 if ( isset( $row->page_len ) )
296 $this->mLength = (int)$row->page_len;
297 if ( isset( $row->page_is_redirect ) )
298 $this->mRedirect = (bool)$row->page_is_redirect;
299 if ( isset( $row->page_latest ) )
300 $this->mLatestID = (int)$row->page_latest;
301 if ( isset( $row->page_content_model ) )
302 $this->mContentModel = strval( $row->page_content_model );
303 else
304 $this->mContentModel = false; # initialized lazily in getContentModel()
305 } else { // page not found
306 $this->mArticleID = 0;
307 $this->mLength = 0;
308 $this->mRedirect = false;
309 $this->mLatestID = 0;
310 $this->mContentModel = false; # initialized lazily in getContentModel()
311 }
312 }
313
314 /**
315 * Create a new Title from a namespace index and a DB key.
316 * It's assumed that $ns and $title are *valid*, for instance when
317 * they came directly from the database or a special page name.
318 * For convenience, spaces are converted to underscores so that
319 * eg user_text fields can be used directly.
320 *
321 * @param $ns Int the namespace of the article
322 * @param $title String the unprefixed database key form
323 * @param $fragment String the link fragment (after the "#")
324 * @param $interwiki String the interwiki prefix
325 * @return Title the new object
326 */
327 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
328 $t = new Title();
329 $t->mInterwiki = $interwiki;
330 $t->mFragment = $fragment;
331 $t->mNamespace = $ns = intval( $ns );
332 $t->mDbkeyform = str_replace( ' ', '_', $title );
333 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
334 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
335 $t->mTextform = str_replace( '_', ' ', $title );
336 $t->mContentModel = false; # initialized lazily in getContentModel()
337 return $t;
338 }
339
340 /**
341 * Create a new Title from a namespace index and a DB key.
342 * The parameters will be checked for validity, which is a bit slower
343 * than makeTitle() but safer for user-provided data.
344 *
345 * @param $ns Int the namespace of the article
346 * @param $title String database key form
347 * @param $fragment String the link fragment (after the "#")
348 * @param $interwiki String interwiki prefix
349 * @return Title the new object, or NULL on an error
350 */
351 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
352 if ( !MWNamespace::exists( $ns ) ) {
353 return null;
354 }
355
356 $t = new Title();
357 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
358 if ( $t->secureAndSplit() ) {
359 return $t;
360 } else {
361 return null;
362 }
363 }
364
365 /**
366 * Create a new Title for the Main Page
367 *
368 * @return Title the new object
369 */
370 public static function newMainPage() {
371 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
372 // Don't give fatal errors if the message is broken
373 if ( !$title ) {
374 $title = Title::newFromText( 'Main Page' );
375 }
376 return $title;
377 }
378
379 /**
380 * Extract a redirect destination from a string and return the
381 * Title, or null if the text doesn't contain a valid redirect
382 * This will only return the very next target, useful for
383 * the redirect table and other checks that don't need full recursion
384 *
385 * @param $text String: Text with possible redirect
386 * @return Title: The corresponding Title
387 * @deprecated since 1.WD, use Content::getRedirectTarget instead.
388 */
389 public static function newFromRedirect( $text ) {
390 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
391 return $content->getRedirectTarget();
392 }
393
394 /**
395 * Extract a redirect destination from a string and return the
396 * Title, or null if the text doesn't contain a valid redirect
397 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
398 * in order to provide (hopefully) the Title of the final destination instead of another redirect
399 *
400 * @param $text String Text with possible redirect
401 * @return Title
402 * @deprecated since 1.WD, use Content::getUltimateRedirectTarget instead.
403 */
404 public static function newFromRedirectRecurse( $text ) {
405 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
406 return $content->getUltimateRedirectTarget();
407 }
408
409 /**
410 * Extract a redirect destination from a string and return an
411 * array of Titles, or null if the text doesn't contain a valid redirect
412 * The last element in the array is the final destination after all redirects
413 * have been resolved (up to $wgMaxRedirects times)
414 *
415 * @param $text String Text with possible redirect
416 * @return Array of Titles, with the destination last
417 * @deprecated since 1.WD, use Content::getRedirectChain instead.
418 */
419 public static function newFromRedirectArray( $text ) {
420 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
421 return $content->getRedirectChain();
422 }
423
424 /**
425 * Get the prefixed DB key associated with an ID
426 *
427 * @param $id Int the page_id of the article
428 * @return Title an object representing the article, or NULL if no such article was found
429 */
430 public static function nameOf( $id ) {
431 $dbr = wfGetDB( DB_SLAVE );
432
433 $s = $dbr->selectRow(
434 'page',
435 array( 'page_namespace', 'page_title' ),
436 array( 'page_id' => $id ),
437 __METHOD__
438 );
439 if ( $s === false ) {
440 return null;
441 }
442
443 $n = self::makeName( $s->page_namespace, $s->page_title );
444 return $n;
445 }
446
447 /**
448 * Get a regex character class describing the legal characters in a link
449 *
450 * @return String the list of characters, not delimited
451 */
452 public static function legalChars() {
453 global $wgLegalTitleChars;
454 return $wgLegalTitleChars;
455 }
456
457 /**
458 * Returns a simple regex that will match on characters and sequences invalid in titles.
459 * Note that this doesn't pick up many things that could be wrong with titles, but that
460 * replacing this regex with something valid will make many titles valid.
461 *
462 * @return String regex string
463 */
464 static function getTitleInvalidRegex() {
465 static $rxTc = false;
466 if ( !$rxTc ) {
467 # Matching titles will be held as illegal.
468 $rxTc = '/' .
469 # Any character not allowed is forbidden...
470 '[^' . self::legalChars() . ']' .
471 # URL percent encoding sequences interfere with the ability
472 # to round-trip titles -- you can't link to them consistently.
473 '|%[0-9A-Fa-f]{2}' .
474 # XML/HTML character references produce similar issues.
475 '|&[A-Za-z0-9\x80-\xff]+;' .
476 '|&#[0-9]+;' .
477 '|&#x[0-9A-Fa-f]+;' .
478 '/S';
479 }
480
481 return $rxTc;
482 }
483
484 /**
485 * Get a string representation of a title suitable for
486 * including in a search index
487 *
488 * @param $ns Int a namespace index
489 * @param $title String text-form main part
490 * @return String a stripped-down title string ready for the search index
491 */
492 public static function indexTitle( $ns, $title ) {
493 global $wgContLang;
494
495 $lc = SearchEngine::legalSearchChars() . '&#;';
496 $t = $wgContLang->normalizeForSearch( $title );
497 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
498 $t = $wgContLang->lc( $t );
499
500 # Handle 's, s'
501 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
502 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
503
504 $t = preg_replace( "/\\s+/", ' ', $t );
505
506 if ( $ns == NS_FILE ) {
507 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
508 }
509 return trim( $t );
510 }
511
512 /**
513 * Make a prefixed DB key from a DB key and a namespace index
514 *
515 * @param $ns Int numerical representation of the namespace
516 * @param $title String the DB key form the title
517 * @param $fragment String The link fragment (after the "#")
518 * @param $interwiki String The interwiki prefix
519 * @return String the prefixed form of the title
520 */
521 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
522 global $wgContLang;
523
524 $namespace = $wgContLang->getNsText( $ns );
525 $name = $namespace == '' ? $title : "$namespace:$title";
526 if ( strval( $interwiki ) != '' ) {
527 $name = "$interwiki:$name";
528 }
529 if ( strval( $fragment ) != '' ) {
530 $name .= '#' . $fragment;
531 }
532 return $name;
533 }
534
535 /**
536 * Escape a text fragment, say from a link, for a URL
537 *
538 * @param $fragment string containing a URL or link fragment (after the "#")
539 * @return String: escaped string
540 */
541 static function escapeFragmentForURL( $fragment ) {
542 # Note that we don't urlencode the fragment. urlencoded Unicode
543 # fragments appear not to work in IE (at least up to 7) or in at least
544 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
545 # to care if they aren't encoded.
546 return Sanitizer::escapeId( $fragment, 'noninitial' );
547 }
548
549 /**
550 * Callback for usort() to do title sorts by (namespace, title)
551 *
552 * @param $a Title
553 * @param $b Title
554 *
555 * @return Integer: result of string comparison, or namespace comparison
556 */
557 public static function compare( $a, $b ) {
558 if ( $a->getNamespace() == $b->getNamespace() ) {
559 return strcmp( $a->getText(), $b->getText() );
560 } else {
561 return $a->getNamespace() - $b->getNamespace();
562 }
563 }
564
565 /**
566 * Determine whether the object refers to a page within
567 * this project.
568 *
569 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
570 */
571 public function isLocal() {
572 if ( $this->mInterwiki != '' ) {
573 return Interwiki::fetch( $this->mInterwiki )->isLocal();
574 } else {
575 return true;
576 }
577 }
578
579 /**
580 * Is this Title interwiki?
581 *
582 * @return Bool
583 */
584 public function isExternal() {
585 return ( $this->mInterwiki != '' );
586 }
587
588 /**
589 * Get the interwiki prefix (or null string)
590 *
591 * @return String Interwiki prefix
592 */
593 public function getInterwiki() {
594 return $this->mInterwiki;
595 }
596
597 /**
598 * Determine whether the object refers to a page within
599 * this project and is transcludable.
600 *
601 * @return Bool TRUE if this is transcludable
602 */
603 public function isTrans() {
604 if ( $this->mInterwiki == '' ) {
605 return false;
606 }
607
608 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
609 }
610
611 /**
612 * Returns the DB name of the distant wiki which owns the object.
613 *
614 * @return String the DB name
615 */
616 public function getTransWikiID() {
617 if ( $this->mInterwiki == '' ) {
618 return false;
619 }
620
621 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
622 }
623
624 /**
625 * Get the text form (spaces not underscores) of the main part
626 *
627 * @return String Main part of the title
628 */
629 public function getText() {
630 return $this->mTextform;
631 }
632
633 /**
634 * Get the URL-encoded form of the main part
635 *
636 * @return String Main part of the title, URL-encoded
637 */
638 public function getPartialURL() {
639 return $this->mUrlform;
640 }
641
642 /**
643 * Get the main part with underscores
644 *
645 * @return String: Main part of the title, with underscores
646 */
647 public function getDBkey() {
648 return $this->mDbkeyform;
649 }
650
651 /**
652 * Get the DB key with the initial letter case as specified by the user
653 *
654 * @return String DB key
655 */
656 function getUserCaseDBKey() {
657 return $this->mUserCaseDBKey;
658 }
659
660 /**
661 * Get the namespace index, i.e. one of the NS_xxxx constants.
662 *
663 * @return Integer: Namespace index
664 */
665 public function getNamespace() {
666 return $this->mNamespace;
667 }
668
669 /**
670 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
671 *
672 * @return String: Content model id
673 */
674 public function getContentModel() {
675 if ( !$this->mContentModel ) {
676 $linkCache = LinkCache::singleton();
677 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
678 }
679
680 if ( !$this->mContentModel ) {
681 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
682 }
683
684 if( !$this->mContentModel ) {
685 throw new MWException( "failed to determin content model!" );
686 }
687
688 return $this->mContentModel;
689 }
690
691 /**
692 * Convenience method for checking a title's content model name
693 *
694 * @param int $id
695 * @return Boolean true if $this->getContentModel() == $id
696 */
697 public function hasContentModel( $id ) {
698 return $this->getContentModel() == $id;
699 }
700
701 /**
702 * Get the namespace text
703 *
704 * @return String: Namespace text
705 */
706 public function getNsText() {
707 global $wgContLang;
708
709 if ( $this->mInterwiki != '' ) {
710 // This probably shouldn't even happen. ohh man, oh yuck.
711 // But for interwiki transclusion it sometimes does.
712 // Shit. Shit shit shit.
713 //
714 // Use the canonical namespaces if possible to try to
715 // resolve a foreign namespace.
716 if ( MWNamespace::exists( $this->mNamespace ) ) {
717 return MWNamespace::getCanonicalName( $this->mNamespace );
718 }
719 }
720
721 if ( $wgContLang->needsGenderDistinction() &&
722 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
723 $gender = GenderCache::singleton()->getGenderOf( $this->getText(), __METHOD__ );
724 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
725 }
726
727 return $wgContLang->getNsText( $this->mNamespace );
728 }
729
730 /**
731 * Get the namespace text of the subject (rather than talk) page
732 *
733 * @return String Namespace text
734 */
735 public function getSubjectNsText() {
736 global $wgContLang;
737 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
738 }
739
740 /**
741 * Get the namespace text of the talk page
742 *
743 * @return String Namespace text
744 */
745 public function getTalkNsText() {
746 global $wgContLang;
747 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
748 }
749
750 /**
751 * Could this title have a corresponding talk page?
752 *
753 * @return Bool TRUE or FALSE
754 */
755 public function canTalk() {
756 return( MWNamespace::canTalk( $this->mNamespace ) );
757 }
758
759 /**
760 * Is this in a namespace that allows actual pages?
761 *
762 * @return Bool
763 * @internal note -- uses hardcoded namespace index instead of constants
764 */
765 public function canExist() {
766 return $this->mNamespace >= NS_MAIN;
767 }
768
769 /**
770 * Can this title be added to a user's watchlist?
771 *
772 * @return Bool TRUE or FALSE
773 */
774 public function isWatchable() {
775 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
776 }
777
778 /**
779 * Returns true if this is a special page.
780 *
781 * @return boolean
782 */
783 public function isSpecialPage() {
784 return $this->getNamespace() == NS_SPECIAL;
785 }
786
787 /**
788 * Returns true if this title resolves to the named special page
789 *
790 * @param $name String The special page name
791 * @return boolean
792 */
793 public function isSpecial( $name ) {
794 if ( $this->isSpecialPage() ) {
795 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
796 if ( $name == $thisName ) {
797 return true;
798 }
799 }
800 return false;
801 }
802
803 /**
804 * If the Title refers to a special page alias which is not the local default, resolve
805 * the alias, and localise the name as necessary. Otherwise, return $this
806 *
807 * @return Title
808 */
809 public function fixSpecialName() {
810 if ( $this->isSpecialPage() ) {
811 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
812 if ( $canonicalName ) {
813 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
814 if ( $localName != $this->mDbkeyform ) {
815 return Title::makeTitle( NS_SPECIAL, $localName );
816 }
817 }
818 }
819 return $this;
820 }
821
822 /**
823 * Returns true if the title is inside the specified namespace.
824 *
825 * Please make use of this instead of comparing to getNamespace()
826 * This function is much more resistant to changes we may make
827 * to namespaces than code that makes direct comparisons.
828 * @param $ns int The namespace
829 * @return bool
830 * @since 1.19
831 */
832 public function inNamespace( $ns ) {
833 return MWNamespace::equals( $this->getNamespace(), $ns );
834 }
835
836 /**
837 * Returns true if the title is inside one of the specified namespaces.
838 *
839 * @param ...$namespaces The namespaces to check for
840 * @return bool
841 * @since 1.19
842 */
843 public function inNamespaces( /* ... */ ) {
844 $namespaces = func_get_args();
845 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
846 $namespaces = $namespaces[0];
847 }
848
849 foreach ( $namespaces as $ns ) {
850 if ( $this->inNamespace( $ns ) ) {
851 return true;
852 }
853 }
854
855 return false;
856 }
857
858 /**
859 * Returns true if the title has the same subject namespace as the
860 * namespace specified.
861 * For example this method will take NS_USER and return true if namespace
862 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
863 * as their subject namespace.
864 *
865 * This is MUCH simpler than individually testing for equivilance
866 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
867 * @since 1.19
868 * @param $ns int
869 * @return bool
870 */
871 public function hasSubjectNamespace( $ns ) {
872 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
873 }
874
875 /**
876 * Is this Title in a namespace which contains content?
877 * In other words, is this a content page, for the purposes of calculating
878 * statistics, etc?
879 *
880 * @return Boolean
881 */
882 public function isContentPage() {
883 return MWNamespace::isContent( $this->getNamespace() );
884 }
885
886 /**
887 * Would anybody with sufficient privileges be able to move this page?
888 * Some pages just aren't movable.
889 *
890 * @return Bool TRUE or FALSE
891 */
892 public function isMovable() {
893 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->getInterwiki() != '' ) {
894 // Interwiki title or immovable namespace. Hooks don't get to override here
895 return false;
896 }
897
898 $result = true;
899 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
900 return $result;
901 }
902
903 /**
904 * Is this the mainpage?
905 * @note Title::newFromText seams to be sufficiently optimized by the title
906 * cache that we don't need to over-optimize by doing direct comparisons and
907 * acidentally creating new bugs where $title->equals( Title::newFromText() )
908 * ends up reporting something differently than $title->isMainPage();
909 *
910 * @since 1.18
911 * @return Bool
912 */
913 public function isMainPage() {
914 return $this->equals( Title::newMainPage() );
915 }
916
917 /**
918 * Is this a subpage?
919 *
920 * @return Bool
921 */
922 public function isSubpage() {
923 return MWNamespace::hasSubpages( $this->mNamespace )
924 ? strpos( $this->getText(), '/' ) !== false
925 : false;
926 }
927
928 /**
929 * Is this a conversion table for the LanguageConverter?
930 *
931 * @return Bool
932 */
933 public function isConversionTable() {
934 return $this->getNamespace() == NS_MEDIAWIKI &&
935 strpos( $this->getText(), 'Conversiontable/' ) === 0;
936 }
937
938 /**
939 * Does that page contain wikitext, or it is JS, CSS or whatever?
940 *
941 * @return Bool
942 */
943 public function isWikitextPage() {
944 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
945 }
946
947 /**
948 * Could this page contain custom CSS or JavaScript for the global UI.
949 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
950 * or CONTENT_MODEL_JAVASCRIPT.
951 *
952 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
953 *
954 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
955 *
956 * @return Bool
957 */
958 public function isCssOrJsPage() {
959 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
960 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
961 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
962
963 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
964 # hook funktions can force this method to return true even outside the mediawiki namespace.
965
966 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
967
968 return $isCssOrJsPage;
969 }
970
971 /**
972 * Is this a .css or .js subpage of a user page?
973 * @return Bool
974 */
975 public function isCssJsSubpage() {
976 return ( NS_USER == $this->mNamespace && $this->isSubpage()
977 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
978 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
979 }
980
981 /**
982 * Trim down a .css or .js subpage title to get the corresponding skin name
983 *
984 * @return string containing skin name from .css or .js subpage title
985 */
986 public function getSkinFromCssJsSubpage() {
987 $subpage = explode( '/', $this->mTextform );
988 $subpage = $subpage[ count( $subpage ) - 1 ];
989 $lastdot = strrpos( $subpage, '.' );
990 if ( $lastdot === false )
991 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
992 return substr( $subpage, 0, $lastdot );
993 }
994
995 /**
996 * Is this a .css subpage of a user page?
997 *
998 * @return Bool
999 */
1000 public function isCssSubpage() {
1001 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1002 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1003 }
1004
1005 /**
1006 * Is this a .js subpage of a user page?
1007 *
1008 * @return Bool
1009 */
1010 public function isJsSubpage() {
1011 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1012 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1013 }
1014
1015 /**
1016 * Is this a talk page of some sort?
1017 *
1018 * @return Bool
1019 */
1020 public function isTalkPage() {
1021 return MWNamespace::isTalk( $this->getNamespace() );
1022 }
1023
1024 /**
1025 * Get a Title object associated with the talk page of this article
1026 *
1027 * @return Title the object for the talk page
1028 */
1029 public function getTalkPage() {
1030 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1031 }
1032
1033 /**
1034 * Get a title object associated with the subject page of this
1035 * talk page
1036 *
1037 * @return Title the object for the subject page
1038 */
1039 public function getSubjectPage() {
1040 // Is this the same title?
1041 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1042 if ( $this->getNamespace() == $subjectNS ) {
1043 return $this;
1044 }
1045 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1046 }
1047
1048 /**
1049 * Get the default namespace index, for when there is no namespace
1050 *
1051 * @return Int Default namespace index
1052 */
1053 public function getDefaultNamespace() {
1054 return $this->mDefaultNamespace;
1055 }
1056
1057 /**
1058 * Get title for search index
1059 *
1060 * @return String a stripped-down title string ready for the
1061 * search index
1062 */
1063 public function getIndexTitle() {
1064 return Title::indexTitle( $this->mNamespace, $this->mTextform );
1065 }
1066
1067 /**
1068 * Get the Title fragment (i.e.\ the bit after the #) in text form
1069 *
1070 * @return String Title fragment
1071 */
1072 public function getFragment() {
1073 return $this->mFragment;
1074 }
1075
1076 /**
1077 * Get the fragment in URL form, including the "#" character if there is one
1078 * @return String Fragment in URL form
1079 */
1080 public function getFragmentForURL() {
1081 if ( $this->mFragment == '' ) {
1082 return '';
1083 } else {
1084 return '#' . Title::escapeFragmentForURL( $this->mFragment );
1085 }
1086 }
1087
1088 /**
1089 * Set the fragment for this title. Removes the first character from the
1090 * specified fragment before setting, so it assumes you're passing it with
1091 * an initial "#".
1092 *
1093 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1094 * Still in active use privately.
1095 *
1096 * @param $fragment String text
1097 */
1098 public function setFragment( $fragment ) {
1099 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1100 }
1101
1102 /**
1103 * Prefix some arbitrary text with the namespace or interwiki prefix
1104 * of this object
1105 *
1106 * @param $name String the text
1107 * @return String the prefixed text
1108 * @private
1109 */
1110 private function prefix( $name ) {
1111 $p = '';
1112 if ( $this->mInterwiki != '' ) {
1113 $p = $this->mInterwiki . ':';
1114 }
1115
1116 if ( 0 != $this->mNamespace ) {
1117 $p .= $this->getNsText() . ':';
1118 }
1119 return $p . $name;
1120 }
1121
1122 /**
1123 * Get the prefixed database key form
1124 *
1125 * @return String the prefixed title, with underscores and
1126 * any interwiki and namespace prefixes
1127 */
1128 public function getPrefixedDBkey() {
1129 $s = $this->prefix( $this->mDbkeyform );
1130 $s = str_replace( ' ', '_', $s );
1131 return $s;
1132 }
1133
1134 /**
1135 * Get the prefixed title with spaces.
1136 * This is the form usually used for display
1137 *
1138 * @return String the prefixed title, with spaces
1139 */
1140 public function getPrefixedText() {
1141 // @todo FIXME: Bad usage of empty() ?
1142 if ( empty( $this->mPrefixedText ) ) {
1143 $s = $this->prefix( $this->mTextform );
1144 $s = str_replace( '_', ' ', $s );
1145 $this->mPrefixedText = $s;
1146 }
1147 return $this->mPrefixedText;
1148 }
1149
1150 /**
1151 * Return a string representation of this title
1152 *
1153 * @return String representation of this title
1154 */
1155 public function __toString() {
1156 return $this->getPrefixedText();
1157 }
1158
1159 /**
1160 * Get the prefixed title with spaces, plus any fragment
1161 * (part beginning with '#')
1162 *
1163 * @return String the prefixed title, with spaces and the fragment, including '#'
1164 */
1165 public function getFullText() {
1166 $text = $this->getPrefixedText();
1167 if ( $this->mFragment != '' ) {
1168 $text .= '#' . $this->mFragment;
1169 }
1170 return $text;
1171 }
1172
1173 /**
1174 * Get the base page name, i.e. the leftmost part before any slashes
1175 *
1176 * @return String Base name
1177 */
1178 public function getBaseText() {
1179 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1180 return $this->getText();
1181 }
1182
1183 $parts = explode( '/', $this->getText() );
1184 # Don't discard the real title if there's no subpage involved
1185 if ( count( $parts ) > 1 ) {
1186 unset( $parts[count( $parts ) - 1] );
1187 }
1188 return implode( '/', $parts );
1189 }
1190
1191 /**
1192 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1193 *
1194 * @return String Subpage name
1195 */
1196 public function getSubpageText() {
1197 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1198 return( $this->mTextform );
1199 }
1200 $parts = explode( '/', $this->mTextform );
1201 return( $parts[count( $parts ) - 1] );
1202 }
1203
1204 /**
1205 * Get the HTML-escaped displayable text form.
1206 * Used for the title field in <a> tags.
1207 *
1208 * @return String the text, including any prefixes
1209 */
1210 public function getEscapedText() {
1211 wfDeprecated( __METHOD__, '1.19' );
1212 return htmlspecialchars( $this->getPrefixedText() );
1213 }
1214
1215 /**
1216 * Get a URL-encoded form of the subpage text
1217 *
1218 * @return String URL-encoded subpage name
1219 */
1220 public function getSubpageUrlForm() {
1221 $text = $this->getSubpageText();
1222 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1223 return( $text );
1224 }
1225
1226 /**
1227 * Get a URL-encoded title (not an actual URL) including interwiki
1228 *
1229 * @return String the URL-encoded form
1230 */
1231 public function getPrefixedURL() {
1232 $s = $this->prefix( $this->mDbkeyform );
1233 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1234 return $s;
1235 }
1236
1237 /**
1238 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1239 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1240 * second argument named variant. This was deprecated in favor
1241 * of passing an array of option with a "variant" key
1242 * Once $query2 is removed for good, this helper can be dropped
1243 * andthe wfArrayToCGI moved to getLocalURL();
1244 *
1245 * @since 1.19 (r105919)
1246 * @param $query
1247 * @param $query2 bool
1248 * @return String
1249 */
1250 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1251 if( $query2 !== false ) {
1252 wfDeprecated( "Title::get{Canonical,Full,Link,Local} method called with a second parameter is deprecated. Add your parameter to an array passed as the first parameter.", "1.19" );
1253 }
1254 if ( is_array( $query ) ) {
1255 $query = wfArrayToCGI( $query );
1256 }
1257 if ( $query2 ) {
1258 if ( is_string( $query2 ) ) {
1259 // $query2 is a string, we will consider this to be
1260 // a deprecated $variant argument and add it to the query
1261 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1262 } else {
1263 $query2 = wfArrayToCGI( $query2 );
1264 }
1265 // If we have $query content add a & to it first
1266 if ( $query ) {
1267 $query .= '&';
1268 }
1269 // Now append the queries together
1270 $query .= $query2;
1271 }
1272 return $query;
1273 }
1274
1275 /**
1276 * Get a real URL referring to this title, with interwiki link and
1277 * fragment
1278 *
1279 * See getLocalURL for the arguments.
1280 *
1281 * @see self::getLocalURL
1282 * @see wfExpandUrl
1283 * @param $proto Protocol type to use in URL
1284 * @return String the URL
1285 */
1286 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1287 $query = self::fixUrlQueryArgs( $query, $query2 );
1288
1289 # Hand off all the decisions on urls to getLocalURL
1290 $url = $this->getLocalURL( $query );
1291
1292 # Expand the url to make it a full url. Note that getLocalURL has the
1293 # potential to output full urls for a variety of reasons, so we use
1294 # wfExpandUrl instead of simply prepending $wgServer
1295 $url = wfExpandUrl( $url, $proto );
1296
1297 # Finally, add the fragment.
1298 $url .= $this->getFragmentForURL();
1299
1300 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1301 return $url;
1302 }
1303
1304 /**
1305 * Get a URL with no fragment or server name. If this page is generated
1306 * with action=render, $wgServer is prepended.
1307 *
1308
1309 * @param $query string|array an optional query string,
1310 * not used for interwiki links. Can be specified as an associative array as well,
1311 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1312 * Some query patterns will trigger various shorturl path replacements.
1313 * @param $query2 Mixed: An optional secondary query array. This one MUST
1314 * be an array. If a string is passed it will be interpreted as a deprecated
1315 * variant argument and urlencoded into a variant= argument.
1316 * This second query argument will be added to the $query
1317 * The second parameter is deprecated since 1.19. Pass it as a key,value
1318 * pair in the first parameter array instead.
1319 *
1320 * @return String the URL
1321 */
1322 public function getLocalURL( $query = '', $query2 = false ) {
1323 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1324
1325 $query = self::fixUrlQueryArgs( $query, $query2 );
1326
1327 $interwiki = Interwiki::fetch( $this->mInterwiki );
1328 if ( $interwiki ) {
1329 $namespace = $this->getNsText();
1330 if ( $namespace != '' ) {
1331 # Can this actually happen? Interwikis shouldn't be parsed.
1332 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1333 $namespace .= ':';
1334 }
1335 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1336 $url = wfAppendQuery( $url, $query );
1337 } else {
1338 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1339 if ( $query == '' ) {
1340 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1341 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1342 } else {
1343 global $wgVariantArticlePath, $wgActionPaths;
1344 $url = false;
1345 $matches = array();
1346
1347 if ( !empty( $wgActionPaths ) &&
1348 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1349 {
1350 $action = urldecode( $matches[2] );
1351 if ( isset( $wgActionPaths[$action] ) ) {
1352 $query = $matches[1];
1353 if ( isset( $matches[4] ) ) {
1354 $query .= $matches[4];
1355 }
1356 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1357 if ( $query != '' ) {
1358 $url = wfAppendQuery( $url, $query );
1359 }
1360 }
1361 }
1362
1363 if ( $url === false &&
1364 $wgVariantArticlePath &&
1365 $this->getPageLanguage()->hasVariants() &&
1366 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1367 {
1368 $variant = urldecode( $matches[1] );
1369 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1370 // Only do the variant replacement if the given variant is a valid
1371 // variant for the page's language.
1372 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1373 $url = str_replace( '$1', $dbkey, $url );
1374 }
1375 }
1376
1377 if ( $url === false ) {
1378 if ( $query == '-' ) {
1379 $query = '';
1380 }
1381 $url = "{$wgScript}?title={$dbkey}&{$query}";
1382 }
1383 }
1384
1385 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1386
1387 // @todo FIXME: This causes breakage in various places when we
1388 // actually expected a local URL and end up with dupe prefixes.
1389 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1390 $url = $wgServer . $url;
1391 }
1392 }
1393 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1394 return $url;
1395 }
1396
1397 /**
1398 * Get a URL that's the simplest URL that will be valid to link, locally,
1399 * to the current Title. It includes the fragment, but does not include
1400 * the server unless action=render is used (or the link is external). If
1401 * there's a fragment but the prefixed text is empty, we just return a link
1402 * to the fragment.
1403 *
1404 * The result obviously should not be URL-escaped, but does need to be
1405 * HTML-escaped if it's being output in HTML.
1406 *
1407 * See getLocalURL for the arguments.
1408 *
1409 * @see self::getLocalURL
1410 * @return String the URL
1411 */
1412 public function getLinkURL( $query = '', $query2 = false ) {
1413 wfProfileIn( __METHOD__ );
1414 if ( $this->isExternal() ) {
1415 $ret = $this->getFullURL( $query, $query2 );
1416 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1417 $ret = $this->getFragmentForURL();
1418 } else {
1419 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1420 }
1421 wfProfileOut( __METHOD__ );
1422 return $ret;
1423 }
1424
1425 /**
1426 * Get an HTML-escaped version of the URL form, suitable for
1427 * using in a link, without a server name or fragment
1428 *
1429 * See getLocalURL for the arguments.
1430 *
1431 * @see self::getLocalURL
1432 * @param $query string
1433 * @param $query2 bool|string
1434 * @return String the URL
1435 */
1436 public function escapeLocalURL( $query = '', $query2 = false ) {
1437 wfDeprecated( __METHOD__, '1.19' );
1438 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1439 }
1440
1441 /**
1442 * Get an HTML-escaped version of the URL form, suitable for
1443 * using in a link, including the server name and fragment
1444 *
1445 * See getLocalURL for the arguments.
1446 *
1447 * @see self::getLocalURL
1448 * @return String the URL
1449 */
1450 public function escapeFullURL( $query = '', $query2 = false ) {
1451 wfDeprecated( __METHOD__, '1.19' );
1452 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1453 }
1454
1455 /**
1456 * Get the URL form for an internal link.
1457 * - Used in various Squid-related code, in case we have a different
1458 * internal hostname for the server from the exposed one.
1459 *
1460 * This uses $wgInternalServer to qualify the path, or $wgServer
1461 * if $wgInternalServer is not set. If the server variable used is
1462 * protocol-relative, the URL will be expanded to http://
1463 *
1464 * See getLocalURL for the arguments.
1465 *
1466 * @see self::getLocalURL
1467 * @return String the URL
1468 */
1469 public function getInternalURL( $query = '', $query2 = false ) {
1470 global $wgInternalServer, $wgServer;
1471 $query = self::fixUrlQueryArgs( $query, $query2 );
1472 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1473 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1474 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1475 return $url;
1476 }
1477
1478 /**
1479 * Get the URL for a canonical link, for use in things like IRC and
1480 * e-mail notifications. Uses $wgCanonicalServer and the
1481 * GetCanonicalURL hook.
1482 *
1483 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1484 *
1485 * See getLocalURL for the arguments.
1486 *
1487 * @see self::getLocalURL
1488 * @return string The URL
1489 * @since 1.18
1490 */
1491 public function getCanonicalURL( $query = '', $query2 = false ) {
1492 $query = self::fixUrlQueryArgs( $query, $query2 );
1493 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1494 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1495 return $url;
1496 }
1497
1498 /**
1499 * HTML-escaped version of getCanonicalURL()
1500 *
1501 * See getLocalURL for the arguments.
1502 *
1503 * @see self::getLocalURL
1504 * @since 1.18
1505 * @return string
1506 */
1507 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1508 wfDeprecated( __METHOD__, '1.19' );
1509 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1510 }
1511
1512 /**
1513 * Get the edit URL for this Title
1514 *
1515 * @return String the URL, or a null string if this is an
1516 * interwiki link
1517 */
1518 public function getEditURL() {
1519 if ( $this->mInterwiki != '' ) {
1520 return '';
1521 }
1522 $s = $this->getLocalURL( 'action=edit' );
1523
1524 return $s;
1525 }
1526
1527 /**
1528 * Is $wgUser watching this page?
1529 *
1530 * @deprecated in 1.20; use User::isWatched() instead.
1531 * @return Bool
1532 */
1533 public function userIsWatching() {
1534 global $wgUser;
1535
1536 if ( is_null( $this->mWatched ) ) {
1537 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1538 $this->mWatched = false;
1539 } else {
1540 $this->mWatched = $wgUser->isWatched( $this );
1541 }
1542 }
1543 return $this->mWatched;
1544 }
1545
1546 /**
1547 * Can $wgUser read this page?
1548 *
1549 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1550 * @return Bool
1551 * @todo fold these checks into userCan()
1552 */
1553 public function userCanRead() {
1554 wfDeprecated( __METHOD__, '1.19' );
1555 return $this->userCan( 'read' );
1556 }
1557
1558 /**
1559 * Can $user perform $action on this page?
1560 * This skips potentially expensive cascading permission checks
1561 * as well as avoids expensive error formatting
1562 *
1563 * Suitable for use for nonessential UI controls in common cases, but
1564 * _not_ for functional access control.
1565 *
1566 * May provide false positives, but should never provide a false negative.
1567 *
1568 * @param $action String action that permission needs to be checked for
1569 * @param $user User to check (since 1.19); $wgUser will be used if not
1570 * provided.
1571 * @return Bool
1572 */
1573 public function quickUserCan( $action, $user = null ) {
1574 return $this->userCan( $action, $user, false );
1575 }
1576
1577 /**
1578 * Can $user perform $action on this page?
1579 *
1580 * @param $action String action that permission needs to be checked for
1581 * @param $user User to check (since 1.19); $wgUser will be used if not
1582 * provided.
1583 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1584 * unnecessary queries.
1585 * @return Bool
1586 */
1587 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1588 if ( !$user instanceof User ) {
1589 global $wgUser;
1590 $user = $wgUser;
1591 }
1592 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1593 }
1594
1595 /**
1596 * Can $user perform $action on this page?
1597 *
1598 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1599 *
1600 * @param $action String action that permission needs to be checked for
1601 * @param $user User to check
1602 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1603 * queries by skipping checks for cascading protections and user blocks.
1604 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1605 * whose corresponding errors may be ignored.
1606 * @return Array of arguments to wfMessage to explain permissions problems.
1607 */
1608 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1609 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1610
1611 // Remove the errors being ignored.
1612 foreach ( $errors as $index => $error ) {
1613 $error_key = is_array( $error ) ? $error[0] : $error;
1614
1615 if ( in_array( $error_key, $ignoreErrors ) ) {
1616 unset( $errors[$index] );
1617 }
1618 }
1619
1620 return $errors;
1621 }
1622
1623 /**
1624 * Permissions checks that fail most often, and which are easiest to test.
1625 *
1626 * @param $action String the action to check
1627 * @param $user User user to check
1628 * @param $errors Array list of current errors
1629 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1630 * @param $short Boolean short circuit on first error
1631 *
1632 * @return Array list of errors
1633 */
1634 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1635 if ( $action == 'create' ) {
1636 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1637 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1638 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1639 }
1640 } elseif ( $action == 'move' ) {
1641 if ( !$user->isAllowed( 'move-rootuserpages' )
1642 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1643 // Show user page-specific message only if the user can move other pages
1644 $errors[] = array( 'cant-move-user-page' );
1645 }
1646
1647 // Check if user is allowed to move files if it's a file
1648 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1649 $errors[] = array( 'movenotallowedfile' );
1650 }
1651
1652 if ( !$user->isAllowed( 'move' ) ) {
1653 // User can't move anything
1654 global $wgGroupPermissions;
1655 $userCanMove = false;
1656 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1657 $userCanMove = $wgGroupPermissions['user']['move'];
1658 }
1659 $autoconfirmedCanMove = false;
1660 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1661 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1662 }
1663 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1664 // custom message if logged-in users without any special rights can move
1665 $errors[] = array( 'movenologintext' );
1666 } else {
1667 $errors[] = array( 'movenotallowed' );
1668 }
1669 }
1670 } elseif ( $action == 'move-target' ) {
1671 if ( !$user->isAllowed( 'move' ) ) {
1672 // User can't move anything
1673 $errors[] = array( 'movenotallowed' );
1674 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1675 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1676 // Show user page-specific message only if the user can move other pages
1677 $errors[] = array( 'cant-move-to-user-page' );
1678 }
1679 } elseif ( !$user->isAllowed( $action ) ) {
1680 $errors[] = $this->missingPermissionError( $action, $short );
1681 }
1682
1683 return $errors;
1684 }
1685
1686 /**
1687 * Add the resulting error code to the errors array
1688 *
1689 * @param $errors Array list of current errors
1690 * @param $result Mixed result of errors
1691 *
1692 * @return Array list of errors
1693 */
1694 private function resultToError( $errors, $result ) {
1695 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1696 // A single array representing an error
1697 $errors[] = $result;
1698 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1699 // A nested array representing multiple errors
1700 $errors = array_merge( $errors, $result );
1701 } elseif ( $result !== '' && is_string( $result ) ) {
1702 // A string representing a message-id
1703 $errors[] = array( $result );
1704 } elseif ( $result === false ) {
1705 // a generic "We don't want them to do that"
1706 $errors[] = array( 'badaccess-group0' );
1707 }
1708 return $errors;
1709 }
1710
1711 /**
1712 * Check various permission hooks
1713 *
1714 * @param $action String the action to check
1715 * @param $user User user to check
1716 * @param $errors Array list of current errors
1717 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1718 * @param $short Boolean short circuit on first error
1719 *
1720 * @return Array list of errors
1721 */
1722 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1723 // Use getUserPermissionsErrors instead
1724 $result = '';
1725 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1726 return $result ? array() : array( array( 'badaccess-group0' ) );
1727 }
1728 // Check getUserPermissionsErrors hook
1729 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1730 $errors = $this->resultToError( $errors, $result );
1731 }
1732 // Check getUserPermissionsErrorsExpensive hook
1733 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1734 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1735 $errors = $this->resultToError( $errors, $result );
1736 }
1737
1738 return $errors;
1739 }
1740
1741 /**
1742 * Check permissions on special pages & namespaces
1743 *
1744 * @param $action String the action to check
1745 * @param $user User user to check
1746 * @param $errors Array list of current errors
1747 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1748 * @param $short Boolean short circuit on first error
1749 *
1750 * @return Array list of errors
1751 */
1752 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1753 # Only 'createaccount' and 'execute' can be performed on
1754 # special pages, which don't actually exist in the DB.
1755 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1756 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1757 $errors[] = array( 'ns-specialprotected' );
1758 }
1759
1760 # Check $wgNamespaceProtection for restricted namespaces
1761 if ( $this->isNamespaceProtected( $user ) ) {
1762 $ns = $this->mNamespace == NS_MAIN ?
1763 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1764 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1765 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1766 }
1767
1768 return $errors;
1769 }
1770
1771 /**
1772 * Check CSS/JS sub-page permissions
1773 *
1774 * @param $action String the action to check
1775 * @param $user User user to check
1776 * @param $errors Array list of current errors
1777 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1778 * @param $short Boolean short circuit on first error
1779 *
1780 * @return Array list of errors
1781 */
1782 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1783 # Protect css/js subpages of user pages
1784 # XXX: this might be better using restrictions
1785 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1786 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1787 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1788 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1789 $errors[] = array( 'customcssprotected' );
1790 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1791 $errors[] = array( 'customjsprotected' );
1792 }
1793 }
1794
1795 return $errors;
1796 }
1797
1798 /**
1799 * Check against page_restrictions table requirements on this
1800 * page. The user must possess all required rights for this
1801 * action.
1802 *
1803 * @param $action String the action to check
1804 * @param $user User user to check
1805 * @param $errors Array list of current errors
1806 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1807 * @param $short Boolean short circuit on first error
1808 *
1809 * @return Array list of errors
1810 */
1811 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1812 foreach ( $this->getRestrictions( $action ) as $right ) {
1813 // Backwards compatibility, rewrite sysop -> protect
1814 if ( $right == 'sysop' ) {
1815 $right = 'protect';
1816 }
1817 if ( $right != '' && !$user->isAllowed( $right ) ) {
1818 // Users with 'editprotected' permission can edit protected pages
1819 // without cascading option turned on.
1820 if ( $action != 'edit' || !$user->isAllowed( 'editprotected' )
1821 || $this->mCascadeRestriction )
1822 {
1823 $errors[] = array( 'protectedpagetext', $right );
1824 }
1825 }
1826 }
1827
1828 return $errors;
1829 }
1830
1831 /**
1832 * Check restrictions on cascading pages.
1833 *
1834 * @param $action String the action to check
1835 * @param $user User to check
1836 * @param $errors Array list of current errors
1837 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1838 * @param $short Boolean short circuit on first error
1839 *
1840 * @return Array list of errors
1841 */
1842 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1843 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1844 # We /could/ use the protection level on the source page, but it's
1845 # fairly ugly as we have to establish a precedence hierarchy for pages
1846 # included by multiple cascade-protected pages. So just restrict
1847 # it to people with 'protect' permission, as they could remove the
1848 # protection anyway.
1849 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1850 # Cascading protection depends on more than this page...
1851 # Several cascading protected pages may include this page...
1852 # Check each cascading level
1853 # This is only for protection restrictions, not for all actions
1854 if ( isset( $restrictions[$action] ) ) {
1855 foreach ( $restrictions[$action] as $right ) {
1856 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1857 if ( $right != '' && !$user->isAllowed( $right ) ) {
1858 $pages = '';
1859 foreach ( $cascadingSources as $page )
1860 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1861 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1862 }
1863 }
1864 }
1865 }
1866
1867 return $errors;
1868 }
1869
1870 /**
1871 * Check action permissions not already checked in checkQuickPermissions
1872 *
1873 * @param $action String the action to check
1874 * @param $user User to check
1875 * @param $errors Array list of current errors
1876 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1877 * @param $short Boolean short circuit on first error
1878 *
1879 * @return Array list of errors
1880 */
1881 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1882 global $wgDeleteRevisionsLimit, $wgLang;
1883
1884 if ( $action == 'protect' ) {
1885 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1886 // If they can't edit, they shouldn't protect.
1887 $errors[] = array( 'protect-cantedit' );
1888 }
1889 } elseif ( $action == 'create' ) {
1890 $title_protection = $this->getTitleProtection();
1891 if( $title_protection ) {
1892 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1893 $title_protection['pt_create_perm'] = 'protect'; // B/C
1894 }
1895 if( $title_protection['pt_create_perm'] == '' ||
1896 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1897 {
1898 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1899 }
1900 }
1901 } elseif ( $action == 'move' ) {
1902 // Check for immobile pages
1903 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1904 // Specific message for this case
1905 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1906 } elseif ( !$this->isMovable() ) {
1907 // Less specific message for rarer cases
1908 $errors[] = array( 'immobile-source-page' );
1909 }
1910 } elseif ( $action == 'move-target' ) {
1911 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1912 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1913 } elseif ( !$this->isMovable() ) {
1914 $errors[] = array( 'immobile-target-page' );
1915 }
1916 } elseif ( $action == 'delete' ) {
1917 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1918 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1919 {
1920 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1921 }
1922 }
1923 return $errors;
1924 }
1925
1926 /**
1927 * Check that the user isn't blocked from editting.
1928 *
1929 * @param $action String the action to check
1930 * @param $user User to check
1931 * @param $errors Array list of current errors
1932 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1933 * @param $short Boolean short circuit on first error
1934 *
1935 * @return Array list of errors
1936 */
1937 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1938 // Account creation blocks handled at userlogin.
1939 // Unblocking handled in SpecialUnblock
1940 if( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1941 return $errors;
1942 }
1943
1944 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1945
1946 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1947 $errors[] = array( 'confirmedittext' );
1948 }
1949
1950 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1951 // Don't block the user from editing their own talk page unless they've been
1952 // explicitly blocked from that too.
1953 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
1954 $block = $user->getBlock();
1955
1956 // This is from OutputPage::blockedPage
1957 // Copied at r23888 by werdna
1958
1959 $id = $user->blockedBy();
1960 $reason = $user->blockedFor();
1961 if ( $reason == '' ) {
1962 $reason = wfMessage( 'blockednoreason' )->text();
1963 }
1964 $ip = $user->getRequest()->getIP();
1965
1966 if ( is_numeric( $id ) ) {
1967 $name = User::whoIs( $id );
1968 } else {
1969 $name = $id;
1970 }
1971
1972 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1973 $blockid = $block->getId();
1974 $blockExpiry = $block->getExpiry();
1975 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true );
1976 if ( $blockExpiry == 'infinity' ) {
1977 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1978 } else {
1979 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1980 }
1981
1982 $intended = strval( $block->getTarget() );
1983
1984 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1985 $blockid, $blockExpiry, $intended, $blockTimestamp );
1986 }
1987
1988 return $errors;
1989 }
1990
1991 /**
1992 * Check that the user is allowed to read this page.
1993 *
1994 * @param $action String the action to check
1995 * @param $user User to check
1996 * @param $errors Array list of current errors
1997 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1998 * @param $short Boolean short circuit on first error
1999 *
2000 * @return Array list of errors
2001 */
2002 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2003 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
2004 static $useShortcut = null;
2005
2006 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2007 if ( is_null( $useShortcut ) ) {
2008 $useShortcut = true;
2009 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2010 # Not a public wiki, so no shortcut
2011 $useShortcut = false;
2012 } elseif ( !empty( $wgRevokePermissions ) ) {
2013 /**
2014 * Iterate through each group with permissions being revoked (key not included since we don't care
2015 * what the group name is), then check if the read permission is being revoked. If it is, then
2016 * we don't use the shortcut below since the user might not be able to read, even though anon
2017 * reading is allowed.
2018 */
2019 foreach ( $wgRevokePermissions as $perms ) {
2020 if ( !empty( $perms['read'] ) ) {
2021 # We might be removing the read right from the user, so no shortcut
2022 $useShortcut = false;
2023 break;
2024 }
2025 }
2026 }
2027 }
2028
2029 $whitelisted = false;
2030 if ( $useShortcut ) {
2031 # Shortcut for public wikis, allows skipping quite a bit of code
2032 $whitelisted = true;
2033 } elseif ( $user->isAllowed( 'read' ) ) {
2034 # If the user is allowed to read pages, he is allowed to read all pages
2035 $whitelisted = true;
2036 } elseif ( $this->isSpecial( 'Userlogin' )
2037 || $this->isSpecial( 'ChangePassword' )
2038 || $this->isSpecial( 'PasswordReset' )
2039 ) {
2040 # Always grant access to the login page.
2041 # Even anons need to be able to log in.
2042 $whitelisted = true;
2043 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2044 # Time to check the whitelist
2045 # Only do these checks is there's something to check against
2046 $name = $this->getPrefixedText();
2047 $dbName = $this->getPrefixedDBKey();
2048
2049 // Check for explicit whitelisting with and without underscores
2050 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2051 $whitelisted = true;
2052 } elseif ( $this->getNamespace() == NS_MAIN ) {
2053 # Old settings might have the title prefixed with
2054 # a colon for main-namespace pages
2055 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2056 $whitelisted = true;
2057 }
2058 } elseif ( $this->isSpecialPage() ) {
2059 # If it's a special page, ditch the subpage bit and check again
2060 $name = $this->getDBkey();
2061 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2062 if ( $name !== false ) {
2063 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2064 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2065 $whitelisted = true;
2066 }
2067 }
2068 }
2069 }
2070
2071 if ( !$whitelisted ) {
2072 # If the title is not whitelisted, give extensions a chance to do so...
2073 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2074 if ( !$whitelisted ) {
2075 $errors[] = $this->missingPermissionError( $action, $short );
2076 }
2077 }
2078
2079 return $errors;
2080 }
2081
2082 /**
2083 * Get a description array when the user doesn't have the right to perform
2084 * $action (i.e. when User::isAllowed() returns false)
2085 *
2086 * @param $action String the action to check
2087 * @param $short Boolean short circuit on first error
2088 * @return Array list of errors
2089 */
2090 private function missingPermissionError( $action, $short ) {
2091 // We avoid expensive display logic for quickUserCan's and such
2092 if ( $short ) {
2093 return array( 'badaccess-group0' );
2094 }
2095
2096 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2097 User::getGroupsWithPermission( $action ) );
2098
2099 if ( count( $groups ) ) {
2100 global $wgLang;
2101 return array(
2102 'badaccess-groups',
2103 $wgLang->commaList( $groups ),
2104 count( $groups )
2105 );
2106 } else {
2107 return array( 'badaccess-group0' );
2108 }
2109 }
2110
2111 /**
2112 * Can $user perform $action on this page? This is an internal function,
2113 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2114 * checks on wfReadOnly() and blocks)
2115 *
2116 * @param $action String action that permission needs to be checked for
2117 * @param $user User to check
2118 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2119 * @param $short Bool Set this to true to stop after the first permission error.
2120 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2121 */
2122 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2123 wfProfileIn( __METHOD__ );
2124
2125 # Read has special handling
2126 if ( $action == 'read' ) {
2127 $checks = array(
2128 'checkPermissionHooks',
2129 'checkReadPermissions',
2130 );
2131 } else {
2132 $checks = array(
2133 'checkQuickPermissions',
2134 'checkPermissionHooks',
2135 'checkSpecialsAndNSPermissions',
2136 'checkCSSandJSPermissions',
2137 'checkPageRestrictions',
2138 'checkCascadingSourcesRestrictions',
2139 'checkActionPermissions',
2140 'checkUserBlock'
2141 );
2142 }
2143
2144 $errors = array();
2145 while( count( $checks ) > 0 &&
2146 !( $short && count( $errors ) > 0 ) ) {
2147 $method = array_shift( $checks );
2148 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2149 }
2150
2151 wfProfileOut( __METHOD__ );
2152 return $errors;
2153 }
2154
2155 /**
2156 * Protect css subpages of user pages: can $wgUser edit
2157 * this page?
2158 *
2159 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2160 * @return Bool
2161 */
2162 public function userCanEditCssSubpage() {
2163 global $wgUser;
2164 wfDeprecated( __METHOD__, '1.19' );
2165 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2166 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2167 }
2168
2169 /**
2170 * Protect js subpages of user pages: can $wgUser edit
2171 * this page?
2172 *
2173 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2174 * @return Bool
2175 */
2176 public function userCanEditJsSubpage() {
2177 global $wgUser;
2178 wfDeprecated( __METHOD__, '1.19' );
2179 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2180 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2181 }
2182
2183 /**
2184 * Get a filtered list of all restriction types supported by this wiki.
2185 * @param bool $exists True to get all restriction types that apply to
2186 * titles that do exist, False for all restriction types that apply to
2187 * titles that do not exist
2188 * @return array
2189 */
2190 public static function getFilteredRestrictionTypes( $exists = true ) {
2191 global $wgRestrictionTypes;
2192 $types = $wgRestrictionTypes;
2193 if ( $exists ) {
2194 # Remove the create restriction for existing titles
2195 $types = array_diff( $types, array( 'create' ) );
2196 } else {
2197 # Only the create and upload restrictions apply to non-existing titles
2198 $types = array_intersect( $types, array( 'create', 'upload' ) );
2199 }
2200 return $types;
2201 }
2202
2203 /**
2204 * Returns restriction types for the current Title
2205 *
2206 * @return array applicable restriction types
2207 */
2208 public function getRestrictionTypes() {
2209 if ( $this->isSpecialPage() ) {
2210 return array();
2211 }
2212
2213 $types = self::getFilteredRestrictionTypes( $this->exists() );
2214
2215 if ( $this->getNamespace() != NS_FILE ) {
2216 # Remove the upload restriction for non-file titles
2217 $types = array_diff( $types, array( 'upload' ) );
2218 }
2219
2220 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2221
2222 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2223 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2224
2225 return $types;
2226 }
2227
2228 /**
2229 * Is this title subject to title protection?
2230 * Title protection is the one applied against creation of such title.
2231 *
2232 * @return Mixed An associative array representing any existent title
2233 * protection, or false if there's none.
2234 */
2235 private function getTitleProtection() {
2236 // Can't protect pages in special namespaces
2237 if ( $this->getNamespace() < 0 ) {
2238 return false;
2239 }
2240
2241 // Can't protect pages that exist.
2242 if ( $this->exists() ) {
2243 return false;
2244 }
2245
2246 if ( !isset( $this->mTitleProtection ) ) {
2247 $dbr = wfGetDB( DB_SLAVE );
2248 $res = $dbr->select( 'protected_titles', '*',
2249 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2250 __METHOD__ );
2251
2252 // fetchRow returns false if there are no rows.
2253 $this->mTitleProtection = $dbr->fetchRow( $res );
2254 }
2255 return $this->mTitleProtection;
2256 }
2257
2258 /**
2259 * Update the title protection status
2260 *
2261 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2262 * @param $create_perm String Permission required for creation
2263 * @param $reason String Reason for protection
2264 * @param $expiry String Expiry timestamp
2265 * @return boolean true
2266 */
2267 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2268 wfDeprecated( __METHOD__, '1.19' );
2269
2270 global $wgUser;
2271
2272 $limit = array( 'create' => $create_perm );
2273 $expiry = array( 'create' => $expiry );
2274
2275 $page = WikiPage::factory( $this );
2276 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2277
2278 return $status->isOK();
2279 }
2280
2281 /**
2282 * Remove any title protection due to page existing
2283 */
2284 public function deleteTitleProtection() {
2285 $dbw = wfGetDB( DB_MASTER );
2286
2287 $dbw->delete(
2288 'protected_titles',
2289 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2290 __METHOD__
2291 );
2292 $this->mTitleProtection = false;
2293 }
2294
2295 /**
2296 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2297 *
2298 * @param $action String Action to check (default: edit)
2299 * @return Bool
2300 */
2301 public function isSemiProtected( $action = 'edit' ) {
2302 if ( $this->exists() ) {
2303 $restrictions = $this->getRestrictions( $action );
2304 if ( count( $restrictions ) > 0 ) {
2305 foreach ( $restrictions as $restriction ) {
2306 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2307 return false;
2308 }
2309 }
2310 } else {
2311 # Not protected
2312 return false;
2313 }
2314 return true;
2315 } else {
2316 # If it doesn't exist, it can't be protected
2317 return false;
2318 }
2319 }
2320
2321 /**
2322 * Does the title correspond to a protected article?
2323 *
2324 * @param $action String the action the page is protected from,
2325 * by default checks all actions.
2326 * @return Bool
2327 */
2328 public function isProtected( $action = '' ) {
2329 global $wgRestrictionLevels;
2330
2331 $restrictionTypes = $this->getRestrictionTypes();
2332
2333 # Special pages have inherent protection
2334 if( $this->isSpecialPage() ) {
2335 return true;
2336 }
2337
2338 # Check regular protection levels
2339 foreach ( $restrictionTypes as $type ) {
2340 if ( $action == $type || $action == '' ) {
2341 $r = $this->getRestrictions( $type );
2342 foreach ( $wgRestrictionLevels as $level ) {
2343 if ( in_array( $level, $r ) && $level != '' ) {
2344 return true;
2345 }
2346 }
2347 }
2348 }
2349
2350 return false;
2351 }
2352
2353 /**
2354 * Determines if $user is unable to edit this page because it has been protected
2355 * by $wgNamespaceProtection.
2356 *
2357 * @param $user User object to check permissions
2358 * @return Bool
2359 */
2360 public function isNamespaceProtected( User $user ) {
2361 global $wgNamespaceProtection;
2362
2363 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2364 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2365 if ( $right != '' && !$user->isAllowed( $right ) ) {
2366 return true;
2367 }
2368 }
2369 }
2370 return false;
2371 }
2372
2373 /**
2374 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2375 *
2376 * @return Bool If the page is subject to cascading restrictions.
2377 */
2378 public function isCascadeProtected() {
2379 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2380 return ( $sources > 0 );
2381 }
2382
2383 /**
2384 * Cascading protection: Get the source of any cascading restrictions on this page.
2385 *
2386 * @param $getPages Bool Whether or not to retrieve the actual pages
2387 * that the restrictions have come from.
2388 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2389 * have come, false for none, or true if such restrictions exist, but $getPages
2390 * was not set. The restriction array is an array of each type, each of which
2391 * contains a array of unique groups.
2392 */
2393 public function getCascadeProtectionSources( $getPages = true ) {
2394 global $wgContLang;
2395 $pagerestrictions = array();
2396
2397 if ( isset( $this->mCascadeSources ) && $getPages ) {
2398 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2399 } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2400 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2401 }
2402
2403 wfProfileIn( __METHOD__ );
2404
2405 $dbr = wfGetDB( DB_SLAVE );
2406
2407 if ( $this->getNamespace() == NS_FILE ) {
2408 $tables = array( 'imagelinks', 'page_restrictions' );
2409 $where_clauses = array(
2410 'il_to' => $this->getDBkey(),
2411 'il_from=pr_page',
2412 'pr_cascade' => 1
2413 );
2414 } else {
2415 $tables = array( 'templatelinks', 'page_restrictions' );
2416 $where_clauses = array(
2417 'tl_namespace' => $this->getNamespace(),
2418 'tl_title' => $this->getDBkey(),
2419 'tl_from=pr_page',
2420 'pr_cascade' => 1
2421 );
2422 }
2423
2424 if ( $getPages ) {
2425 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2426 'pr_expiry', 'pr_type', 'pr_level' );
2427 $where_clauses[] = 'page_id=pr_page';
2428 $tables[] = 'page';
2429 } else {
2430 $cols = array( 'pr_expiry' );
2431 }
2432
2433 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2434
2435 $sources = $getPages ? array() : false;
2436 $now = wfTimestampNow();
2437 $purgeExpired = false;
2438
2439 foreach ( $res as $row ) {
2440 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2441 if ( $expiry > $now ) {
2442 if ( $getPages ) {
2443 $page_id = $row->pr_page;
2444 $page_ns = $row->page_namespace;
2445 $page_title = $row->page_title;
2446 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2447 # Add groups needed for each restriction type if its not already there
2448 # Make sure this restriction type still exists
2449
2450 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2451 $pagerestrictions[$row->pr_type] = array();
2452 }
2453
2454 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2455 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2456 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2457 }
2458 } else {
2459 $sources = true;
2460 }
2461 } else {
2462 // Trigger lazy purge of expired restrictions from the db
2463 $purgeExpired = true;
2464 }
2465 }
2466 if ( $purgeExpired ) {
2467 Title::purgeExpiredRestrictions();
2468 }
2469
2470 if ( $getPages ) {
2471 $this->mCascadeSources = $sources;
2472 $this->mCascadingRestrictions = $pagerestrictions;
2473 } else {
2474 $this->mHasCascadingRestrictions = $sources;
2475 }
2476
2477 wfProfileOut( __METHOD__ );
2478 return array( $sources, $pagerestrictions );
2479 }
2480
2481 /**
2482 * Accessor/initialisation for mRestrictions
2483 *
2484 * @param $action String action that permission needs to be checked for
2485 * @return Array of Strings the array of groups allowed to edit this article
2486 */
2487 public function getRestrictions( $action ) {
2488 if ( !$this->mRestrictionsLoaded ) {
2489 $this->loadRestrictions();
2490 }
2491 return isset( $this->mRestrictions[$action] )
2492 ? $this->mRestrictions[$action]
2493 : array();
2494 }
2495
2496 /**
2497 * Get the expiry time for the restriction against a given action
2498 *
2499 * @param $action
2500 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2501 * or not protected at all, or false if the action is not recognised.
2502 */
2503 public function getRestrictionExpiry( $action ) {
2504 if ( !$this->mRestrictionsLoaded ) {
2505 $this->loadRestrictions();
2506 }
2507 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2508 }
2509
2510 /**
2511 * Returns cascading restrictions for the current article
2512 *
2513 * @return Boolean
2514 */
2515 function areRestrictionsCascading() {
2516 if ( !$this->mRestrictionsLoaded ) {
2517 $this->loadRestrictions();
2518 }
2519
2520 return $this->mCascadeRestriction;
2521 }
2522
2523 /**
2524 * Loads a string into mRestrictions array
2525 *
2526 * @param $res Resource restrictions as an SQL result.
2527 * @param $oldFashionedRestrictions String comma-separated list of page
2528 * restrictions from page table (pre 1.10)
2529 */
2530 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2531 $rows = array();
2532
2533 foreach ( $res as $row ) {
2534 $rows[] = $row;
2535 }
2536
2537 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2538 }
2539
2540 /**
2541 * Compiles list of active page restrictions from both page table (pre 1.10)
2542 * and page_restrictions table for this existing page.
2543 * Public for usage by LiquidThreads.
2544 *
2545 * @param $rows array of db result objects
2546 * @param $oldFashionedRestrictions string comma-separated list of page
2547 * restrictions from page table (pre 1.10)
2548 */
2549 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2550 global $wgContLang;
2551 $dbr = wfGetDB( DB_SLAVE );
2552
2553 $restrictionTypes = $this->getRestrictionTypes();
2554
2555 foreach ( $restrictionTypes as $type ) {
2556 $this->mRestrictions[$type] = array();
2557 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2558 }
2559
2560 $this->mCascadeRestriction = false;
2561
2562 # Backwards-compatibility: also load the restrictions from the page record (old format).
2563
2564 if ( $oldFashionedRestrictions === null ) {
2565 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2566 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2567 }
2568
2569 if ( $oldFashionedRestrictions != '' ) {
2570
2571 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2572 $temp = explode( '=', trim( $restrict ) );
2573 if ( count( $temp ) == 1 ) {
2574 // old old format should be treated as edit/move restriction
2575 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2576 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2577 } else {
2578 $restriction = trim( $temp[1] );
2579 if( $restriction != '' ) { //some old entries are empty
2580 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2581 }
2582 }
2583 }
2584
2585 $this->mOldRestrictions = true;
2586
2587 }
2588
2589 if ( count( $rows ) ) {
2590 # Current system - load second to make them override.
2591 $now = wfTimestampNow();
2592 $purgeExpired = false;
2593
2594 # Cycle through all the restrictions.
2595 foreach ( $rows as $row ) {
2596
2597 // Don't take care of restrictions types that aren't allowed
2598 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2599 continue;
2600
2601 // This code should be refactored, now that it's being used more generally,
2602 // But I don't really see any harm in leaving it in Block for now -werdna
2603 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2604
2605 // Only apply the restrictions if they haven't expired!
2606 if ( !$expiry || $expiry > $now ) {
2607 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2608 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2609
2610 $this->mCascadeRestriction |= $row->pr_cascade;
2611 } else {
2612 // Trigger a lazy purge of expired restrictions
2613 $purgeExpired = true;
2614 }
2615 }
2616
2617 if ( $purgeExpired ) {
2618 Title::purgeExpiredRestrictions();
2619 }
2620 }
2621
2622 $this->mRestrictionsLoaded = true;
2623 }
2624
2625 /**
2626 * Load restrictions from the page_restrictions table
2627 *
2628 * @param $oldFashionedRestrictions String comma-separated list of page
2629 * restrictions from page table (pre 1.10)
2630 */
2631 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2632 global $wgContLang;
2633 if ( !$this->mRestrictionsLoaded ) {
2634 if ( $this->exists() ) {
2635 $dbr = wfGetDB( DB_SLAVE );
2636
2637 $res = $dbr->select(
2638 'page_restrictions',
2639 '*',
2640 array( 'pr_page' => $this->getArticleID() ),
2641 __METHOD__
2642 );
2643
2644 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2645 } else {
2646 $title_protection = $this->getTitleProtection();
2647
2648 if ( $title_protection ) {
2649 $now = wfTimestampNow();
2650 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2651
2652 if ( !$expiry || $expiry > $now ) {
2653 // Apply the restrictions
2654 $this->mRestrictionsExpiry['create'] = $expiry;
2655 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2656 } else { // Get rid of the old restrictions
2657 Title::purgeExpiredRestrictions();
2658 $this->mTitleProtection = false;
2659 }
2660 } else {
2661 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2662 }
2663 $this->mRestrictionsLoaded = true;
2664 }
2665 }
2666 }
2667
2668 /**
2669 * Flush the protection cache in this object and force reload from the database.
2670 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2671 */
2672 public function flushRestrictions() {
2673 $this->mRestrictionsLoaded = false;
2674 $this->mTitleProtection = null;
2675 }
2676
2677 /**
2678 * Purge expired restrictions from the page_restrictions table
2679 */
2680 static function purgeExpiredRestrictions() {
2681 $dbw = wfGetDB( DB_MASTER );
2682 $dbw->delete(
2683 'page_restrictions',
2684 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2685 __METHOD__
2686 );
2687
2688 $dbw->delete(
2689 'protected_titles',
2690 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2691 __METHOD__
2692 );
2693 }
2694
2695 /**
2696 * Does this have subpages? (Warning, usually requires an extra DB query.)
2697 *
2698 * @return Bool
2699 */
2700 public function hasSubpages() {
2701 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
2702 # Duh
2703 return false;
2704 }
2705
2706 # We dynamically add a member variable for the purpose of this method
2707 # alone to cache the result. There's no point in having it hanging
2708 # around uninitialized in every Title object; therefore we only add it
2709 # if needed and don't declare it statically.
2710 if ( isset( $this->mHasSubpages ) ) {
2711 return $this->mHasSubpages;
2712 }
2713
2714 $subpages = $this->getSubpages( 1 );
2715 if ( $subpages instanceof TitleArray ) {
2716 return $this->mHasSubpages = (bool)$subpages->count();
2717 }
2718 return $this->mHasSubpages = false;
2719 }
2720
2721 /**
2722 * Get all subpages of this page.
2723 *
2724 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2725 * @return mixed TitleArray, or empty array if this page's namespace
2726 * doesn't allow subpages
2727 */
2728 public function getSubpages( $limit = -1 ) {
2729 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
2730 return array();
2731 }
2732
2733 $dbr = wfGetDB( DB_SLAVE );
2734 $conds['page_namespace'] = $this->getNamespace();
2735 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2736 $options = array();
2737 if ( $limit > -1 ) {
2738 $options['LIMIT'] = $limit;
2739 }
2740 return $this->mSubpages = TitleArray::newFromResult(
2741 $dbr->select( 'page',
2742 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2743 $conds,
2744 __METHOD__,
2745 $options
2746 )
2747 );
2748 }
2749
2750 /**
2751 * Is there a version of this page in the deletion archive?
2752 *
2753 * @return Int the number of archived revisions
2754 */
2755 public function isDeleted() {
2756 if ( $this->getNamespace() < 0 ) {
2757 $n = 0;
2758 } else {
2759 $dbr = wfGetDB( DB_SLAVE );
2760
2761 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2762 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2763 __METHOD__
2764 );
2765 if ( $this->getNamespace() == NS_FILE ) {
2766 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2767 array( 'fa_name' => $this->getDBkey() ),
2768 __METHOD__
2769 );
2770 }
2771 }
2772 return (int)$n;
2773 }
2774
2775 /**
2776 * Is there a version of this page in the deletion archive?
2777 *
2778 * @return Boolean
2779 */
2780 public function isDeletedQuick() {
2781 if ( $this->getNamespace() < 0 ) {
2782 return false;
2783 }
2784 $dbr = wfGetDB( DB_SLAVE );
2785 $deleted = (bool)$dbr->selectField( 'archive', '1',
2786 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2787 __METHOD__
2788 );
2789 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2790 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2791 array( 'fa_name' => $this->getDBkey() ),
2792 __METHOD__
2793 );
2794 }
2795 return $deleted;
2796 }
2797
2798 /**
2799 * Get the article ID for this Title from the link cache,
2800 * adding it if necessary
2801 *
2802 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2803 * for update
2804 * @return Int the ID
2805 */
2806 public function getArticleID( $flags = 0 ) {
2807 if ( $this->getNamespace() < 0 ) {
2808 return $this->mArticleID = 0;
2809 }
2810 $linkCache = LinkCache::singleton();
2811 if ( $flags & self::GAID_FOR_UPDATE ) {
2812 $oldUpdate = $linkCache->forUpdate( true );
2813 $linkCache->clearLink( $this );
2814 $this->mArticleID = $linkCache->addLinkObj( $this );
2815 $linkCache->forUpdate( $oldUpdate );
2816 } else {
2817 if ( -1 == $this->mArticleID ) {
2818 $this->mArticleID = $linkCache->addLinkObj( $this );
2819 }
2820 }
2821 return $this->mArticleID;
2822 }
2823
2824 /**
2825 * Is this an article that is a redirect page?
2826 * Uses link cache, adding it if necessary
2827 *
2828 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2829 * @return Bool
2830 */
2831 public function isRedirect( $flags = 0 ) {
2832 if ( !is_null( $this->mRedirect ) ) {
2833 return $this->mRedirect;
2834 }
2835 # Calling getArticleID() loads the field from cache as needed
2836 if ( !$this->getArticleID( $flags ) ) {
2837 return $this->mRedirect = false;
2838 }
2839
2840 $linkCache = LinkCache::singleton();
2841 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2842 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
2843 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2844 # as a stop gap, perhaps log this, but don't throw an exception?
2845 throw new MWException( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2846 }
2847
2848 $this->mRedirect = (bool)$cached;
2849
2850 return $this->mRedirect;
2851 }
2852
2853 /**
2854 * What is the length of this page?
2855 * Uses link cache, adding it if necessary
2856 *
2857 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2858 * @return Int
2859 */
2860 public function getLength( $flags = 0 ) {
2861 if ( $this->mLength != -1 ) {
2862 return $this->mLength;
2863 }
2864 # Calling getArticleID() loads the field from cache as needed
2865 if ( !$this->getArticleID( $flags ) ) {
2866 return $this->mLength = 0;
2867 }
2868 $linkCache = LinkCache::singleton();
2869 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
2870 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
2871 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2872 # as a stop gap, perhaps log this, but don't throw an exception?
2873 throw new MWException( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2874 }
2875
2876 $this->mLength = intval( $cached );
2877
2878 return $this->mLength;
2879 }
2880
2881 /**
2882 * What is the page_latest field for this page?
2883 *
2884 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2885 * @return Int or 0 if the page doesn't exist
2886 */
2887 public function getLatestRevID( $flags = 0 ) {
2888 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
2889 return intval( $this->mLatestID );
2890 }
2891 # Calling getArticleID() loads the field from cache as needed
2892 if ( !$this->getArticleID( $flags ) ) {
2893 return $this->mLatestID = 0;
2894 }
2895 $linkCache = LinkCache::singleton();
2896 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
2897 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
2898 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2899 # as a stop gap, perhaps log this, but don't throw an exception?
2900 throw new MWException( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2901 }
2902
2903 $this->mLatestID = intval( $cached );
2904
2905 return $this->mLatestID;
2906 }
2907
2908 /**
2909 * This clears some fields in this object, and clears any associated
2910 * keys in the "bad links" section of the link cache.
2911 *
2912 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2913 * loading of the new page_id. It's also called from
2914 * WikiPage::doDeleteArticleReal()
2915 *
2916 * @param $newid Int the new Article ID
2917 */
2918 public function resetArticleID( $newid ) {
2919 $linkCache = LinkCache::singleton();
2920 $linkCache->clearLink( $this );
2921
2922 if ( $newid === false ) {
2923 $this->mArticleID = -1;
2924 } else {
2925 $this->mArticleID = intval( $newid );
2926 }
2927 $this->mRestrictionsLoaded = false;
2928 $this->mRestrictions = array();
2929 $this->mRedirect = null;
2930 $this->mLength = -1;
2931 $this->mLatestID = false;
2932 $this->mContentModel = false;
2933 $this->mEstimateRevisions = null;
2934 }
2935
2936 /**
2937 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2938 *
2939 * @param $text String containing title to capitalize
2940 * @param $ns int namespace index, defaults to NS_MAIN
2941 * @return String containing capitalized title
2942 */
2943 public static function capitalize( $text, $ns = NS_MAIN ) {
2944 global $wgContLang;
2945
2946 if ( MWNamespace::isCapitalized( $ns ) ) {
2947 return $wgContLang->ucfirst( $text );
2948 } else {
2949 return $text;
2950 }
2951 }
2952
2953 /**
2954 * Secure and split - main initialisation function for this object
2955 *
2956 * Assumes that mDbkeyform has been set, and is urldecoded
2957 * and uses underscores, but not otherwise munged. This function
2958 * removes illegal characters, splits off the interwiki and
2959 * namespace prefixes, sets the other forms, and canonicalizes
2960 * everything.
2961 *
2962 * @return Bool true on success
2963 */
2964 private function secureAndSplit() {
2965 global $wgContLang, $wgLocalInterwiki;
2966
2967 # Initialisation
2968 $this->mInterwiki = $this->mFragment = '';
2969 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2970
2971 $dbkey = $this->mDbkeyform;
2972
2973 # Strip Unicode bidi override characters.
2974 # Sometimes they slip into cut-n-pasted page titles, where the
2975 # override chars get included in list displays.
2976 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2977
2978 # Clean up whitespace
2979 # Note: use of the /u option on preg_replace here will cause
2980 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2981 # conveniently disabling them.
2982 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2983 $dbkey = trim( $dbkey, '_' );
2984
2985 if ( $dbkey == '' ) {
2986 return false;
2987 }
2988
2989 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2990 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2991 return false;
2992 }
2993
2994 $this->mDbkeyform = $dbkey;
2995
2996 # Initial colon indicates main namespace rather than specified default
2997 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2998 if ( ':' == $dbkey[0] ) {
2999 $this->mNamespace = NS_MAIN;
3000 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3001 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3002 }
3003
3004 # Namespace or interwiki prefix
3005 $firstPass = true;
3006 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3007 do {
3008 $m = array();
3009 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3010 $p = $m[1];
3011 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3012 # Ordinary namespace
3013 $dbkey = $m[2];
3014 $this->mNamespace = $ns;
3015 # For Talk:X pages, check if X has a "namespace" prefix
3016 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
3017 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3018 # Disallow Talk:File:x type titles...
3019 return false;
3020 } elseif ( Interwiki::isValidInterwiki( $x[1] ) ) {
3021 # Disallow Talk:Interwiki:x type titles...
3022 return false;
3023 }
3024 }
3025 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
3026 if ( !$firstPass ) {
3027 # Can't make a local interwiki link to an interwiki link.
3028 # That's just crazy!
3029 return false;
3030 }
3031
3032 # Interwiki link
3033 $dbkey = $m[2];
3034 $this->mInterwiki = $wgContLang->lc( $p );
3035
3036 # Redundant interwiki prefix to the local wiki
3037 if ( $wgLocalInterwiki !== false
3038 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
3039 {
3040 if ( $dbkey == '' ) {
3041 # Can't have an empty self-link
3042 return false;
3043 }
3044 $this->mInterwiki = '';
3045 $firstPass = false;
3046 # Do another namespace split...
3047 continue;
3048 }
3049
3050 # If there's an initial colon after the interwiki, that also
3051 # resets the default namespace
3052 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3053 $this->mNamespace = NS_MAIN;
3054 $dbkey = substr( $dbkey, 1 );
3055 }
3056 }
3057 # If there's no recognized interwiki or namespace,
3058 # then let the colon expression be part of the title.
3059 }
3060 break;
3061 } while ( true );
3062
3063 # We already know that some pages won't be in the database!
3064 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
3065 $this->mArticleID = 0;
3066 }
3067 $fragment = strstr( $dbkey, '#' );
3068 if ( false !== $fragment ) {
3069 $this->setFragment( $fragment );
3070 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3071 # remove whitespace again: prevents "Foo_bar_#"
3072 # becoming "Foo_bar_"
3073 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3074 }
3075
3076 # Reject illegal characters.
3077 $rxTc = self::getTitleInvalidRegex();
3078 if ( preg_match( $rxTc, $dbkey ) ) {
3079 return false;
3080 }
3081
3082 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3083 # reachable due to the way web browsers deal with 'relative' URLs.
3084 # Also, they conflict with subpage syntax. Forbid them explicitly.
3085 if ( strpos( $dbkey, '.' ) !== false &&
3086 ( $dbkey === '.' || $dbkey === '..' ||
3087 strpos( $dbkey, './' ) === 0 ||
3088 strpos( $dbkey, '../' ) === 0 ||
3089 strpos( $dbkey, '/./' ) !== false ||
3090 strpos( $dbkey, '/../' ) !== false ||
3091 substr( $dbkey, -2 ) == '/.' ||
3092 substr( $dbkey, -3 ) == '/..' ) )
3093 {
3094 return false;
3095 }
3096
3097 # Magic tilde sequences? Nu-uh!
3098 if ( strpos( $dbkey, '~~~' ) !== false ) {
3099 return false;
3100 }
3101
3102 # Limit the size of titles to 255 bytes. This is typically the size of the
3103 # underlying database field. We make an exception for special pages, which
3104 # don't need to be stored in the database, and may edge over 255 bytes due
3105 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3106 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
3107 strlen( $dbkey ) > 512 )
3108 {
3109 return false;
3110 }
3111
3112 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3113 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3114 # other site might be case-sensitive.
3115 $this->mUserCaseDBKey = $dbkey;
3116 if ( $this->mInterwiki == '' ) {
3117 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
3118 }
3119
3120 # Can't make a link to a namespace alone... "empty" local links can only be
3121 # self-links with a fragment identifier.
3122 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
3123 return false;
3124 }
3125
3126 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3127 // IP names are not allowed for accounts, and can only be referring to
3128 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3129 // there are numerous ways to present the same IP. Having sp:contribs scan
3130 // them all is silly and having some show the edits and others not is
3131 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3132 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
3133 ? IP::sanitizeIP( $dbkey )
3134 : $dbkey;
3135
3136 // Any remaining initial :s are illegal.
3137 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3138 return false;
3139 }
3140
3141 # Fill fields
3142 $this->mDbkeyform = $dbkey;
3143 $this->mUrlform = wfUrlencode( $dbkey );
3144
3145 $this->mTextform = str_replace( '_', ' ', $dbkey );
3146
3147 return true;
3148 }
3149
3150 /**
3151 * Get an array of Title objects linking to this Title
3152 * Also stores the IDs in the link cache.
3153 *
3154 * WARNING: do not use this function on arbitrary user-supplied titles!
3155 * On heavily-used templates it will max out the memory.
3156 *
3157 * @param $options Array: may be FOR UPDATE
3158 * @param $table String: table name
3159 * @param $prefix String: fields prefix
3160 * @return Array of Title objects linking here
3161 */
3162 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3163 if ( count( $options ) > 0 ) {
3164 $db = wfGetDB( DB_MASTER );
3165 } else {
3166 $db = wfGetDB( DB_SLAVE );
3167 }
3168
3169 $res = $db->select(
3170 array( 'page', $table ),
3171 self::getSelectFields(),
3172 array(
3173 "{$prefix}_from=page_id",
3174 "{$prefix}_namespace" => $this->getNamespace(),
3175 "{$prefix}_title" => $this->getDBkey() ),
3176 __METHOD__,
3177 $options
3178 );
3179
3180 $retVal = array();
3181 if ( $res->numRows() ) {
3182 $linkCache = LinkCache::singleton();
3183 foreach ( $res as $row ) {
3184 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3185 if ( $titleObj ) {
3186 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3187 $retVal[] = $titleObj;
3188 }
3189 }
3190 }
3191 return $retVal;
3192 }
3193
3194 /**
3195 * Get an array of Title objects using this Title as a template
3196 * Also stores the IDs in the link cache.
3197 *
3198 * WARNING: do not use this function on arbitrary user-supplied titles!
3199 * On heavily-used templates it will max out the memory.
3200 *
3201 * @param $options Array: may be FOR UPDATE
3202 * @return Array of Title the Title objects linking here
3203 */
3204 public function getTemplateLinksTo( $options = array() ) {
3205 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3206 }
3207
3208 /**
3209 * Get an array of Title objects linked from this Title
3210 * Also stores the IDs in the link cache.
3211 *
3212 * WARNING: do not use this function on arbitrary user-supplied titles!
3213 * On heavily-used templates it will max out the memory.
3214 *
3215 * @param $options Array: may be FOR UPDATE
3216 * @param $table String: table name
3217 * @param $prefix String: fields prefix
3218 * @return Array of Title objects linking here
3219 */
3220 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3221 global $wgContentHandlerUseDB;
3222
3223 $id = $this->getArticleID();
3224
3225 # If the page doesn't exist; there can't be any link from this page
3226 if ( !$id ) {
3227 return array();
3228 }
3229
3230 if ( count( $options ) > 0 ) {
3231 $db = wfGetDB( DB_MASTER );
3232 } else {
3233 $db = wfGetDB( DB_SLAVE );
3234 }
3235
3236 $namespaceFiled = "{$prefix}_namespace";
3237 $titleField = "{$prefix}_title";
3238
3239 $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' );
3240 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3241
3242 $res = $db->select(
3243 array( $table, 'page' ),
3244 $fields,
3245 array( "{$prefix}_from" => $id ),
3246 __METHOD__,
3247 $options,
3248 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3249 );
3250
3251 $retVal = array();
3252 if ( $res->numRows() ) {
3253 $linkCache = LinkCache::singleton();
3254 foreach ( $res as $row ) {
3255 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3256 if ( $titleObj ) {
3257 if ( $row->page_id ) {
3258 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3259 } else {
3260 $linkCache->addBadLinkObj( $titleObj );
3261 }
3262 $retVal[] = $titleObj;
3263 }
3264 }
3265 }
3266 return $retVal;
3267 }
3268
3269 /**
3270 * Get an array of Title objects used on this Title as a template
3271 * Also stores the IDs in the link cache.
3272 *
3273 * WARNING: do not use this function on arbitrary user-supplied titles!
3274 * On heavily-used templates it will max out the memory.
3275 *
3276 * @param $options Array: may be FOR UPDATE
3277 * @return Array of Title the Title objects used here
3278 */
3279 public function getTemplateLinksFrom( $options = array() ) {
3280 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3281 }
3282
3283 /**
3284 * Get an array of Title objects referring to non-existent articles linked from this page
3285 *
3286 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3287 * @return Array of Title the Title objects
3288 */
3289 public function getBrokenLinksFrom() {
3290 if ( $this->getArticleID() == 0 ) {
3291 # All links from article ID 0 are false positives
3292 return array();
3293 }
3294
3295 $dbr = wfGetDB( DB_SLAVE );
3296 $res = $dbr->select(
3297 array( 'page', 'pagelinks' ),
3298 array( 'pl_namespace', 'pl_title' ),
3299 array(
3300 'pl_from' => $this->getArticleID(),
3301 'page_namespace IS NULL'
3302 ),
3303 __METHOD__, array(),
3304 array(
3305 'page' => array(
3306 'LEFT JOIN',
3307 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3308 )
3309 )
3310 );
3311
3312 $retVal = array();
3313 foreach ( $res as $row ) {
3314 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3315 }
3316 return $retVal;
3317 }
3318
3319
3320 /**
3321 * Get a list of URLs to purge from the Squid cache when this
3322 * page changes
3323 *
3324 * @return Array of String the URLs
3325 */
3326 public function getSquidURLs() {
3327 $urls = array(
3328 $this->getInternalURL(),
3329 $this->getInternalURL( 'action=history' )
3330 );
3331
3332 $pageLang = $this->getPageLanguage();
3333 if ( $pageLang->hasVariants() ) {
3334 $variants = $pageLang->getVariants();
3335 foreach ( $variants as $vCode ) {
3336 $urls[] = $this->getInternalURL( '', $vCode );
3337 }
3338 }
3339
3340 return $urls;
3341 }
3342
3343 /**
3344 * Purge all applicable Squid URLs
3345 */
3346 public function purgeSquid() {
3347 global $wgUseSquid;
3348 if ( $wgUseSquid ) {
3349 $urls = $this->getSquidURLs();
3350 $u = new SquidUpdate( $urls );
3351 $u->doUpdate();
3352 }
3353 }
3354
3355 /**
3356 * Move this page without authentication
3357 *
3358 * @param $nt Title the new page Title
3359 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3360 */
3361 public function moveNoAuth( &$nt ) {
3362 return $this->moveTo( $nt, false );
3363 }
3364
3365 /**
3366 * Check whether a given move operation would be valid.
3367 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3368 *
3369 * @param $nt Title the new title
3370 * @param $auth Bool indicates whether $wgUser's permissions
3371 * should be checked
3372 * @param $reason String is the log summary of the move, used for spam checking
3373 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3374 */
3375 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3376 global $wgUser;
3377
3378 $errors = array();
3379 if ( !$nt ) {
3380 // Normally we'd add this to $errors, but we'll get
3381 // lots of syntax errors if $nt is not an object
3382 return array( array( 'badtitletext' ) );
3383 }
3384 if ( $this->equals( $nt ) ) {
3385 $errors[] = array( 'selfmove' );
3386 }
3387 if ( !$this->isMovable() ) {
3388 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3389 }
3390 if ( $nt->getInterwiki() != '' ) {
3391 $errors[] = array( 'immobile-target-namespace-iw' );
3392 }
3393 if ( !$nt->isMovable() ) {
3394 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3395 }
3396
3397 $oldid = $this->getArticleID();
3398 $newid = $nt->getArticleID();
3399
3400 if ( strlen( $nt->getDBkey() ) < 1 ) {
3401 $errors[] = array( 'articleexists' );
3402 }
3403 if ( ( $this->getDBkey() == '' ) ||
3404 ( !$oldid ) ||
3405 ( $nt->getDBkey() == '' ) ) {
3406 $errors[] = array( 'badarticleerror' );
3407 }
3408
3409 // Image-specific checks
3410 if ( $this->getNamespace() == NS_FILE ) {
3411 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3412 }
3413
3414 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3415 $errors[] = array( 'nonfile-cannot-move-to-file' );
3416 }
3417
3418 if ( $auth ) {
3419 $errors = wfMergeErrorArrays( $errors,
3420 $this->getUserPermissionsErrors( 'move', $wgUser ),
3421 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3422 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3423 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3424 }
3425
3426 $match = EditPage::matchSummarySpamRegex( $reason );
3427 if ( $match !== false ) {
3428 // This is kind of lame, won't display nice
3429 $errors[] = array( 'spamprotectiontext' );
3430 }
3431
3432 $err = null;
3433 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3434 $errors[] = array( 'hookaborted', $err );
3435 }
3436
3437 # The move is allowed only if (1) the target doesn't exist, or
3438 # (2) the target is a redirect to the source, and has no history
3439 # (so we can undo bad moves right after they're done).
3440
3441 if ( 0 != $newid ) { # Target exists; check for validity
3442 if ( !$this->isValidMoveTarget( $nt ) ) {
3443 $errors[] = array( 'articleexists' );
3444 }
3445 } else {
3446 $tp = $nt->getTitleProtection();
3447 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3448 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3449 $errors[] = array( 'cantmove-titleprotected' );
3450 }
3451 }
3452 if ( empty( $errors ) ) {
3453 return true;
3454 }
3455 return $errors;
3456 }
3457
3458 /**
3459 * Check if the requested move target is a valid file move target
3460 * @param Title $nt Target title
3461 * @return array List of errors
3462 */
3463 protected function validateFileMoveOperation( $nt ) {
3464 global $wgUser;
3465
3466 $errors = array();
3467
3468 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3469
3470 $file = wfLocalFile( $this );
3471 if ( $file->exists() ) {
3472 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3473 $errors[] = array( 'imageinvalidfilename' );
3474 }
3475 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3476 $errors[] = array( 'imagetypemismatch' );
3477 }
3478 }
3479
3480 if ( $nt->getNamespace() != NS_FILE ) {
3481 $errors[] = array( 'imagenocrossnamespace' );
3482 // From here we want to do checks on a file object, so if we can't
3483 // create one, we must return.
3484 return $errors;
3485 }
3486
3487 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3488
3489 $destFile = wfLocalFile( $nt );
3490 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3491 $errors[] = array( 'file-exists-sharedrepo' );
3492 }
3493
3494 return $errors;
3495 }
3496
3497 /**
3498 * Move a title to a new location
3499 *
3500 * @param $nt Title the new title
3501 * @param $auth Bool indicates whether $wgUser's permissions
3502 * should be checked
3503 * @param $reason String the reason for the move
3504 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3505 * Ignored if the user doesn't have the suppressredirect right.
3506 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3507 */
3508 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3509 global $wgUser;
3510 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3511 if ( is_array( $err ) ) {
3512 // Auto-block user's IP if the account was "hard" blocked
3513 $wgUser->spreadAnyEditBlock();
3514 return $err;
3515 }
3516 // Check suppressredirect permission
3517 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3518 $createRedirect = true;
3519 }
3520
3521 // If it is a file, move it first.
3522 // It is done before all other moving stuff is done because it's hard to revert.
3523 $dbw = wfGetDB( DB_MASTER );
3524 if ( $this->getNamespace() == NS_FILE ) {
3525 $file = wfLocalFile( $this );
3526 if ( $file->exists() ) {
3527 $status = $file->move( $nt );
3528 if ( !$status->isOk() ) {
3529 return $status->getErrorsArray();
3530 }
3531 }
3532 // Clear RepoGroup process cache
3533 RepoGroup::singleton()->clearCache( $this );
3534 RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache
3535 }
3536
3537 $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own.
3538 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3539 $protected = $this->isProtected();
3540
3541 // Do the actual move
3542 $this->moveToInternal( $nt, $reason, $createRedirect );
3543
3544 // Refresh the sortkey for this row. Be careful to avoid resetting
3545 // cl_timestamp, which may disturb time-based lists on some sites.
3546 $prefixes = $dbw->select(
3547 'categorylinks',
3548 array( 'cl_sortkey_prefix', 'cl_to' ),
3549 array( 'cl_from' => $pageid ),
3550 __METHOD__
3551 );
3552 foreach ( $prefixes as $prefixRow ) {
3553 $prefix = $prefixRow->cl_sortkey_prefix;
3554 $catTo = $prefixRow->cl_to;
3555 $dbw->update( 'categorylinks',
3556 array(
3557 'cl_sortkey' => Collation::singleton()->getSortKey(
3558 $nt->getCategorySortkey( $prefix ) ),
3559 'cl_timestamp=cl_timestamp' ),
3560 array(
3561 'cl_from' => $pageid,
3562 'cl_to' => $catTo ),
3563 __METHOD__
3564 );
3565 }
3566
3567 $redirid = $this->getArticleID();
3568
3569 if ( $protected ) {
3570 # Protect the redirect title as the title used to be...
3571 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3572 array(
3573 'pr_page' => $redirid,
3574 'pr_type' => 'pr_type',
3575 'pr_level' => 'pr_level',
3576 'pr_cascade' => 'pr_cascade',
3577 'pr_user' => 'pr_user',
3578 'pr_expiry' => 'pr_expiry'
3579 ),
3580 array( 'pr_page' => $pageid ),
3581 __METHOD__,
3582 array( 'IGNORE' )
3583 );
3584 # Update the protection log
3585 $log = new LogPage( 'protect' );
3586 $comment = wfMessage(
3587 'prot_1movedto2',
3588 $this->getPrefixedText(),
3589 $nt->getPrefixedText()
3590 )->inContentLanguage()->text();
3591 if ( $reason ) {
3592 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3593 }
3594 // @todo FIXME: $params?
3595 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3596 }
3597
3598 # Update watchlists
3599 $oldnamespace = $this->getNamespace() & ~1;
3600 $newnamespace = $nt->getNamespace() & ~1;
3601 $oldtitle = $this->getDBkey();
3602 $newtitle = $nt->getDBkey();
3603
3604 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3605 WatchedItem::duplicateEntries( $this, $nt );
3606 }
3607
3608 $dbw->commit( __METHOD__ );
3609
3610 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3611 return true;
3612 }
3613
3614 /**
3615 * Move page to a title which is either a redirect to the
3616 * source page or nonexistent
3617 *
3618 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3619 * @param $reason String The reason for the move
3620 * @param $createRedirect Bool Whether to leave a redirect at the old title. Does not check
3621 * if the user has the suppressredirect right
3622 * @throws MWException
3623 */
3624 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3625 global $wgUser, $wgContLang;
3626
3627 if ( $nt->exists() ) {
3628 $moveOverRedirect = true;
3629 $logType = 'move_redir';
3630 } else {
3631 $moveOverRedirect = false;
3632 $logType = 'move';
3633 }
3634
3635 $redirectSuppressed = !$createRedirect;
3636
3637 $logEntry = new ManualLogEntry( 'move', $logType );
3638 $logEntry->setPerformer( $wgUser );
3639 $logEntry->setTarget( $this );
3640 $logEntry->setComment( $reason );
3641 $logEntry->setParameters( array(
3642 '4::target' => $nt->getPrefixedText(),
3643 '5::noredir' => $redirectSuppressed ? '1': '0',
3644 ) );
3645
3646 $formatter = LogFormatter::newFromEntry( $logEntry );
3647 $formatter->setContext( RequestContext::newExtraneousContext( $this ) );
3648 $comment = $formatter->getPlainActionText();
3649 if ( $reason ) {
3650 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3651 }
3652 # Truncate for whole multibyte characters.
3653 $comment = $wgContLang->truncate( $comment, 255 );
3654
3655 $oldid = $this->getArticleID();
3656
3657 $dbw = wfGetDB( DB_MASTER );
3658
3659 $newpage = WikiPage::factory( $nt );
3660
3661 if ( $moveOverRedirect ) {
3662 $newid = $nt->getArticleID();
3663
3664 # Delete the old redirect. We don't save it to history since
3665 # by definition if we've got here it's rather uninteresting.
3666 # We have to remove it so that the next step doesn't trigger
3667 # a conflict on the unique namespace+title index...
3668 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3669
3670 $newpage->doDeleteUpdates( $newid );
3671 }
3672
3673 # Save a null revision in the page's history notifying of the move
3674 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3675 if ( !is_object( $nullRevision ) ) {
3676 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3677 }
3678 $nullRevId = $nullRevision->insertOn( $dbw );
3679
3680 # Change the name of the target page:
3681 $dbw->update( 'page',
3682 /* SET */ array(
3683 'page_namespace' => $nt->getNamespace(),
3684 'page_title' => $nt->getDBkey(),
3685 ),
3686 /* WHERE */ array( 'page_id' => $oldid ),
3687 __METHOD__
3688 );
3689
3690 $this->resetArticleID( 0 );
3691 $nt->resetArticleID( $oldid );
3692
3693 $newpage->updateRevisionOn( $dbw, $nullRevision );
3694
3695 wfRunHooks( 'NewRevisionFromEditComplete',
3696 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3697
3698 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3699
3700 if ( !$moveOverRedirect ) {
3701 WikiPage::onArticleCreate( $nt );
3702 }
3703
3704 # Recreate the redirect, this time in the other direction.
3705 if ( $redirectSuppressed ) {
3706 WikiPage::onArticleDelete( $this );
3707 } else {
3708 $mwRedir = MagicWord::get( 'redirect' );
3709 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3710 $redirectArticle = WikiPage::factory( $this );
3711 $newid = $redirectArticle->insertOn( $dbw );
3712 if ( $newid ) { // sanity
3713 $redirectRevision = new Revision( array(
3714 'page' => $newid,
3715 'comment' => $comment,
3716 'text' => $redirectText ) );
3717 $redirectRevision->insertOn( $dbw );
3718 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3719
3720 wfRunHooks( 'NewRevisionFromEditComplete',
3721 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3722
3723 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3724 }
3725 }
3726
3727 # Log the move
3728 $logid = $logEntry->insert();
3729 $logEntry->publish( $logid );
3730 }
3731
3732 /**
3733 * Move this page's subpages to be subpages of $nt
3734 *
3735 * @param $nt Title Move target
3736 * @param $auth bool Whether $wgUser's permissions should be checked
3737 * @param $reason string The reason for the move
3738 * @param $createRedirect bool Whether to create redirects from the old subpages to
3739 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3740 * @return mixed array with old page titles as keys, and strings (new page titles) or
3741 * arrays (errors) as values, or an error array with numeric indices if no pages
3742 * were moved
3743 */
3744 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3745 global $wgMaximumMovedPages;
3746 // Check permissions
3747 if ( !$this->userCan( 'move-subpages' ) ) {
3748 return array( 'cant-move-subpages' );
3749 }
3750 // Do the source and target namespaces support subpages?
3751 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3752 return array( 'namespace-nosubpages',
3753 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3754 }
3755 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3756 return array( 'namespace-nosubpages',
3757 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3758 }
3759
3760 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3761 $retval = array();
3762 $count = 0;
3763 foreach ( $subpages as $oldSubpage ) {
3764 $count++;
3765 if ( $count > $wgMaximumMovedPages ) {
3766 $retval[$oldSubpage->getPrefixedTitle()] =
3767 array( 'movepage-max-pages',
3768 $wgMaximumMovedPages );
3769 break;
3770 }
3771
3772 // We don't know whether this function was called before
3773 // or after moving the root page, so check both
3774 // $this and $nt
3775 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3776 $oldSubpage->getArticleID() == $nt->getArticleID() )
3777 {
3778 // When moving a page to a subpage of itself,
3779 // don't move it twice
3780 continue;
3781 }
3782 $newPageName = preg_replace(
3783 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3784 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3785 $oldSubpage->getDBkey() );
3786 if ( $oldSubpage->isTalkPage() ) {
3787 $newNs = $nt->getTalkPage()->getNamespace();
3788 } else {
3789 $newNs = $nt->getSubjectPage()->getNamespace();
3790 }
3791 # Bug 14385: we need makeTitleSafe because the new page names may
3792 # be longer than 255 characters.
3793 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3794
3795 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3796 if ( $success === true ) {
3797 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3798 } else {
3799 $retval[$oldSubpage->getPrefixedText()] = $success;
3800 }
3801 }
3802 return $retval;
3803 }
3804
3805 /**
3806 * Checks if this page is just a one-rev redirect.
3807 * Adds lock, so don't use just for light purposes.
3808 *
3809 * @return Bool
3810 */
3811 public function isSingleRevRedirect() {
3812 global $wgContentHandlerUseDB;
3813
3814 $dbw = wfGetDB( DB_MASTER );
3815
3816 # Is it a redirect?
3817 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3818 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3819
3820 $row = $dbw->selectRow( 'page',
3821 $fields,
3822 $this->pageCond(),
3823 __METHOD__,
3824 array( 'FOR UPDATE' )
3825 );
3826 # Cache some fields we may want
3827 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3828 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3829 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3830 $this->mContentModel = $row && isset( $row->page_content_model ) ? strval( $row->page_content_model ) : false;
3831 if ( !$this->mRedirect ) {
3832 return false;
3833 }
3834 # Does the article have a history?
3835 $row = $dbw->selectField( array( 'page', 'revision' ),
3836 'rev_id',
3837 array( 'page_namespace' => $this->getNamespace(),
3838 'page_title' => $this->getDBkey(),
3839 'page_id=rev_page',
3840 'page_latest != rev_id'
3841 ),
3842 __METHOD__,
3843 array( 'FOR UPDATE' )
3844 );
3845 # Return true if there was no history
3846 return ( $row === false );
3847 }
3848
3849 /**
3850 * Checks if $this can be moved to a given Title
3851 * - Selects for update, so don't call it unless you mean business
3852 *
3853 * @param $nt Title the new title to check
3854 * @return Bool
3855 */
3856 public function isValidMoveTarget( $nt ) {
3857 # Is it an existing file?
3858 if ( $nt->getNamespace() == NS_FILE ) {
3859 $file = wfLocalFile( $nt );
3860 if ( $file->exists() ) {
3861 wfDebug( __METHOD__ . ": file exists\n" );
3862 return false;
3863 }
3864 }
3865 # Is it a redirect with no history?
3866 if ( !$nt->isSingleRevRedirect() ) {
3867 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3868 return false;
3869 }
3870 # Get the article text
3871 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3872 if( !is_object( $rev ) ){
3873 return false;
3874 }
3875 $content = $rev->getContent();
3876 # Does the redirect point to the source?
3877 # Or is it a broken self-redirect, usually caused by namespace collisions?
3878 $redirTitle = $content->getRedirectTarget();
3879
3880 if ( $redirTitle ) {
3881 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3882 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3883 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3884 return false;
3885 } else {
3886 return true;
3887 }
3888 } else {
3889 # Fail safe (not a redirect after all. strange.)
3890 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3891 " is a redirect, but it doesn't contain a valid redirect.\n" );
3892 return false;
3893 }
3894 }
3895
3896 /**
3897 * Get categories to which this Title belongs and return an array of
3898 * categories' names.
3899 *
3900 * @return Array of parents in the form:
3901 * $parent => $currentarticle
3902 */
3903 public function getParentCategories() {
3904 global $wgContLang;
3905
3906 $data = array();
3907
3908 $titleKey = $this->getArticleID();
3909
3910 if ( $titleKey === 0 ) {
3911 return $data;
3912 }
3913
3914 $dbr = wfGetDB( DB_SLAVE );
3915
3916 $res = $dbr->select( 'categorylinks', '*',
3917 array(
3918 'cl_from' => $titleKey,
3919 ),
3920 __METHOD__,
3921 array()
3922 );
3923
3924 if ( $dbr->numRows( $res ) > 0 ) {
3925 foreach ( $res as $row ) {
3926 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3927 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3928 }
3929 }
3930 return $data;
3931 }
3932
3933 /**
3934 * Get a tree of parent categories
3935 *
3936 * @param $children Array with the children in the keys, to check for circular refs
3937 * @return Array Tree of parent categories
3938 */
3939 public function getParentCategoryTree( $children = array() ) {
3940 $stack = array();
3941 $parents = $this->getParentCategories();
3942
3943 if ( $parents ) {
3944 foreach ( $parents as $parent => $current ) {
3945 if ( array_key_exists( $parent, $children ) ) {
3946 # Circular reference
3947 $stack[$parent] = array();
3948 } else {
3949 $nt = Title::newFromText( $parent );
3950 if ( $nt ) {
3951 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3952 }
3953 }
3954 }
3955 }
3956
3957 return $stack;
3958 }
3959
3960 /**
3961 * Get an associative array for selecting this title from
3962 * the "page" table
3963 *
3964 * @return Array suitable for the $where parameter of DB::select()
3965 */
3966 public function pageCond() {
3967 if ( $this->mArticleID > 0 ) {
3968 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3969 return array( 'page_id' => $this->mArticleID );
3970 } else {
3971 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3972 }
3973 }
3974
3975 /**
3976 * Get the revision ID of the previous revision
3977 *
3978 * @param $revId Int Revision ID. Get the revision that was before this one.
3979 * @param $flags Int Title::GAID_FOR_UPDATE
3980 * @return Int|Bool Old revision ID, or FALSE if none exists
3981 */
3982 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3983 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3984 $revId = $db->selectField( 'revision', 'rev_id',
3985 array(
3986 'rev_page' => $this->getArticleID( $flags ),
3987 'rev_id < ' . intval( $revId )
3988 ),
3989 __METHOD__,
3990 array( 'ORDER BY' => 'rev_id DESC' )
3991 );
3992
3993 if ( $revId === false ) {
3994 return false;
3995 } else {
3996 return intval( $revId );
3997 }
3998 }
3999
4000 /**
4001 * Get the revision ID of the next revision
4002 *
4003 * @param $revId Int Revision ID. Get the revision that was after this one.
4004 * @param $flags Int Title::GAID_FOR_UPDATE
4005 * @return Int|Bool Next revision ID, or FALSE if none exists
4006 */
4007 public function getNextRevisionID( $revId, $flags = 0 ) {
4008 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4009 $revId = $db->selectField( 'revision', 'rev_id',
4010 array(
4011 'rev_page' => $this->getArticleID( $flags ),
4012 'rev_id > ' . intval( $revId )
4013 ),
4014 __METHOD__,
4015 array( 'ORDER BY' => 'rev_id' )
4016 );
4017
4018 if ( $revId === false ) {
4019 return false;
4020 } else {
4021 return intval( $revId );
4022 }
4023 }
4024
4025 /**
4026 * Get the first revision of the page
4027 *
4028 * @param $flags Int Title::GAID_FOR_UPDATE
4029 * @return Revision|Null if page doesn't exist
4030 */
4031 public function getFirstRevision( $flags = 0 ) {
4032 $pageId = $this->getArticleID( $flags );
4033 if ( $pageId ) {
4034 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4035 $row = $db->selectRow( 'revision', Revision::selectFields(),
4036 array( 'rev_page' => $pageId ),
4037 __METHOD__,
4038 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4039 );
4040 if ( $row ) {
4041 return new Revision( $row );
4042 }
4043 }
4044 return null;
4045 }
4046
4047 /**
4048 * Get the oldest revision timestamp of this page
4049 *
4050 * @param $flags Int Title::GAID_FOR_UPDATE
4051 * @return String: MW timestamp
4052 */
4053 public function getEarliestRevTime( $flags = 0 ) {
4054 $rev = $this->getFirstRevision( $flags );
4055 return $rev ? $rev->getTimestamp() : null;
4056 }
4057
4058 /**
4059 * Check if this is a new page
4060 *
4061 * @return bool
4062 */
4063 public function isNewPage() {
4064 $dbr = wfGetDB( DB_SLAVE );
4065 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4066 }
4067
4068 /**
4069 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4070 *
4071 * @return bool
4072 */
4073 public function isBigDeletion() {
4074 global $wgDeleteRevisionsLimit;
4075
4076 if ( !$wgDeleteRevisionsLimit ) {
4077 return false;
4078 }
4079
4080 $revCount = $this->estimateRevisionCount();
4081 return $revCount > $wgDeleteRevisionsLimit;
4082 }
4083
4084 /**
4085 * Get the approximate revision count of this page.
4086 *
4087 * @return int
4088 */
4089 public function estimateRevisionCount() {
4090 if ( !$this->exists() ) {
4091 return 0;
4092 }
4093
4094 if ( $this->mEstimateRevisions === null ) {
4095 $dbr = wfGetDB( DB_SLAVE );
4096 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4097 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4098 }
4099
4100 return $this->mEstimateRevisions;
4101 }
4102
4103 /**
4104 * Get the number of revisions between the given revision.
4105 * Used for diffs and other things that really need it.
4106 *
4107 * @param $old int|Revision Old revision or rev ID (first before range)
4108 * @param $new int|Revision New revision or rev ID (first after range)
4109 * @return Int Number of revisions between these revisions.
4110 */
4111 public function countRevisionsBetween( $old, $new ) {
4112 if ( !( $old instanceof Revision ) ) {
4113 $old = Revision::newFromTitle( $this, (int)$old );
4114 }
4115 if ( !( $new instanceof Revision ) ) {
4116 $new = Revision::newFromTitle( $this, (int)$new );
4117 }
4118 if ( !$old || !$new ) {
4119 return 0; // nothing to compare
4120 }
4121 $dbr = wfGetDB( DB_SLAVE );
4122 return (int)$dbr->selectField( 'revision', 'count(*)',
4123 array(
4124 'rev_page' => $this->getArticleID(),
4125 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4126 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4127 ),
4128 __METHOD__
4129 );
4130 }
4131
4132 /**
4133 * Get the number of authors between the given revisions or revision IDs.
4134 * Used for diffs and other things that really need it.
4135 *
4136 * @param $old int|Revision Old revision or rev ID (first before range by default)
4137 * @param $new int|Revision New revision or rev ID (first after range by default)
4138 * @param $limit int Maximum number of authors
4139 * @param $options string|array (Optional): Single option, or an array of options:
4140 * 'include_old' Include $old in the range; $new is excluded.
4141 * 'include_new' Include $new in the range; $old is excluded.
4142 * 'include_both' Include both $old and $new in the range.
4143 * Unknown option values are ignored.
4144 * @return int Number of revision authors in the range; zero if not both revisions exist
4145 */
4146 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4147 if ( !( $old instanceof Revision ) ) {
4148 $old = Revision::newFromTitle( $this, (int)$old );
4149 }
4150 if ( !( $new instanceof Revision ) ) {
4151 $new = Revision::newFromTitle( $this, (int)$new );
4152 }
4153 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4154 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4155 // in the sanity check below?
4156 if ( !$old || !$new ) {
4157 return 0; // nothing to compare
4158 }
4159 $old_cmp = '>';
4160 $new_cmp = '<';
4161 $options = (array) $options;
4162 if ( in_array( 'include_old', $options ) ) {
4163 $old_cmp = '>=';
4164 }
4165 if ( in_array( 'include_new', $options ) ) {
4166 $new_cmp = '<=';
4167 }
4168 if ( in_array( 'include_both', $options ) ) {
4169 $old_cmp = '>=';
4170 $new_cmp = '<=';
4171 }
4172 // No DB query needed if $old and $new are the same or successive revisions:
4173 if ( $old->getId() === $new->getId() ) {
4174 return ( $old_cmp === '>' && $new_cmp === '<' ) ? 0 : 1;
4175 } else if ( $old->getId() === $new->getParentId() ) {
4176 if ( $old_cmp === '>' || $new_cmp === '<' ) {
4177 return ( $old_cmp === '>' && $new_cmp === '<' ) ? 0 : 1;
4178 }
4179 return ( $old->getRawUserText() === $new->getRawUserText() ) ? 1 : 2;
4180 }
4181 $dbr = wfGetDB( DB_SLAVE );
4182 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4183 array(
4184 'rev_page' => $this->getArticleID(),
4185 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4186 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4187 ), __METHOD__,
4188 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4189 );
4190 return (int)$dbr->numRows( $res );
4191 }
4192
4193 /**
4194 * Compare with another title.
4195 *
4196 * @param $title Title
4197 * @return Bool
4198 */
4199 public function equals( Title $title ) {
4200 // Note: === is necessary for proper matching of number-like titles.
4201 return $this->getInterwiki() === $title->getInterwiki()
4202 && $this->getNamespace() == $title->getNamespace()
4203 && $this->getDBkey() === $title->getDBkey();
4204 }
4205
4206 /**
4207 * Check if this title is a subpage of another title
4208 *
4209 * @param $title Title
4210 * @return Bool
4211 */
4212 public function isSubpageOf( Title $title ) {
4213 return $this->getInterwiki() === $title->getInterwiki()
4214 && $this->getNamespace() == $title->getNamespace()
4215 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4216 }
4217
4218 /**
4219 * Check if page exists. For historical reasons, this function simply
4220 * checks for the existence of the title in the page table, and will
4221 * thus return false for interwiki links, special pages and the like.
4222 * If you want to know if a title can be meaningfully viewed, you should
4223 * probably call the isKnown() method instead.
4224 *
4225 * @return Bool
4226 */
4227 public function exists() {
4228 return $this->getArticleID() != 0;
4229 }
4230
4231 /**
4232 * Should links to this title be shown as potentially viewable (i.e. as
4233 * "bluelinks"), even if there's no record by this title in the page
4234 * table?
4235 *
4236 * This function is semi-deprecated for public use, as well as somewhat
4237 * misleadingly named. You probably just want to call isKnown(), which
4238 * calls this function internally.
4239 *
4240 * (ISSUE: Most of these checks are cheap, but the file existence check
4241 * can potentially be quite expensive. Including it here fixes a lot of
4242 * existing code, but we might want to add an optional parameter to skip
4243 * it and any other expensive checks.)
4244 *
4245 * @return Bool
4246 */
4247 public function isAlwaysKnown() {
4248 $isKnown = null;
4249
4250 /**
4251 * Allows overriding default behaviour for determining if a page exists.
4252 * If $isKnown is kept as null, regular checks happen. If it's
4253 * a boolean, this value is returned by the isKnown method.
4254 *
4255 * @since 1.20
4256 *
4257 * @param Title $title
4258 * @param boolean|null $isKnown
4259 */
4260 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4261
4262 if ( !is_null( $isKnown ) ) {
4263 return $isKnown;
4264 }
4265
4266 if ( $this->mInterwiki != '' ) {
4267 return true; // any interwiki link might be viewable, for all we know
4268 }
4269
4270 switch( $this->mNamespace ) {
4271 case NS_MEDIA:
4272 case NS_FILE:
4273 // file exists, possibly in a foreign repo
4274 return (bool)wfFindFile( $this );
4275 case NS_SPECIAL:
4276 // valid special page
4277 return SpecialPageFactory::exists( $this->getDBkey() );
4278 case NS_MAIN:
4279 // selflink, possibly with fragment
4280 return $this->mDbkeyform == '';
4281 case NS_MEDIAWIKI:
4282 // known system message
4283 return $this->hasSourceText() !== false;
4284 default:
4285 return false;
4286 }
4287 }
4288
4289 /**
4290 * Does this title refer to a page that can (or might) be meaningfully
4291 * viewed? In particular, this function may be used to determine if
4292 * links to the title should be rendered as "bluelinks" (as opposed to
4293 * "redlinks" to non-existent pages).
4294 * Adding something else to this function will cause inconsistency
4295 * since LinkHolderArray calls isAlwaysKnown() and does its own
4296 * page existence check.
4297 *
4298 * @return Bool
4299 */
4300 public function isKnown() {
4301 return $this->isAlwaysKnown() || $this->exists();
4302 }
4303
4304 /**
4305 * Does this page have source text?
4306 *
4307 * @return Boolean
4308 */
4309 public function hasSourceText() {
4310 if ( $this->exists() ) {
4311 return true;
4312 }
4313
4314 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4315 // If the page doesn't exist but is a known system message, default
4316 // message content will be displayed, same for language subpages-
4317 // Use always content language to avoid loading hundreds of languages
4318 // to get the link color.
4319 global $wgContLang;
4320 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4321 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4322 return $message->exists();
4323 }
4324
4325 return false;
4326 }
4327
4328 /**
4329 * Get the default message text or false if the message doesn't exist
4330 *
4331 * @return String or false
4332 */
4333 public function getDefaultMessageText() {
4334 global $wgContLang;
4335
4336 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4337 return false;
4338 }
4339
4340 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4341 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4342
4343 if ( $message->exists() ) {
4344 return $message->plain();
4345 } else {
4346 return false;
4347 }
4348 }
4349
4350 /**
4351 * Updates page_touched for this page; called from LinksUpdate.php
4352 *
4353 * @return Bool true if the update succeded
4354 */
4355 public function invalidateCache() {
4356 if ( wfReadOnly() ) {
4357 return false;
4358 }
4359 $dbw = wfGetDB( DB_MASTER );
4360 $success = $dbw->update(
4361 'page',
4362 array( 'page_touched' => $dbw->timestamp() ),
4363 $this->pageCond(),
4364 __METHOD__
4365 );
4366 HTMLFileCache::clearFileCache( $this );
4367 return $success;
4368 }
4369
4370 /**
4371 * Update page_touched timestamps and send squid purge messages for
4372 * pages linking to this title. May be sent to the job queue depending
4373 * on the number of links. Typically called on create and delete.
4374 */
4375 public function touchLinks() {
4376 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4377 $u->doUpdate();
4378
4379 if ( $this->getNamespace() == NS_CATEGORY ) {
4380 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4381 $u->doUpdate();
4382 }
4383 }
4384
4385 /**
4386 * Get the last touched timestamp
4387 *
4388 * @param $db DatabaseBase: optional db
4389 * @return String last-touched timestamp
4390 */
4391 public function getTouched( $db = null ) {
4392 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4393 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4394 return $touched;
4395 }
4396
4397 /**
4398 * Get the timestamp when this page was updated since the user last saw it.
4399 *
4400 * @param $user User
4401 * @return String|Null
4402 */
4403 public function getNotificationTimestamp( $user = null ) {
4404 global $wgUser, $wgShowUpdatedMarker;
4405 // Assume current user if none given
4406 if ( !$user ) {
4407 $user = $wgUser;
4408 }
4409 // Check cache first
4410 $uid = $user->getId();
4411 // avoid isset here, as it'll return false for null entries
4412 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4413 return $this->mNotificationTimestamp[$uid];
4414 }
4415 if ( !$uid || !$wgShowUpdatedMarker ) {
4416 return $this->mNotificationTimestamp[$uid] = false;
4417 }
4418 // Don't cache too much!
4419 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4420 $this->mNotificationTimestamp = array();
4421 }
4422 $dbr = wfGetDB( DB_SLAVE );
4423 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4424 'wl_notificationtimestamp',
4425 array(
4426 'wl_user' => $user->getId(),
4427 'wl_namespace' => $this->getNamespace(),
4428 'wl_title' => $this->getDBkey(),
4429 ),
4430 __METHOD__
4431 );
4432 return $this->mNotificationTimestamp[$uid];
4433 }
4434
4435 /**
4436 * Generate strings used for xml 'id' names in monobook tabs
4437 *
4438 * @param $prepend string defaults to 'nstab-'
4439 * @return String XML 'id' name
4440 */
4441 public function getNamespaceKey( $prepend = 'nstab-' ) {
4442 global $wgContLang;
4443 // Gets the subject namespace if this title
4444 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4445 // Checks if cononical namespace name exists for namespace
4446 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4447 // Uses canonical namespace name
4448 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4449 } else {
4450 // Uses text of namespace
4451 $namespaceKey = $this->getSubjectNsText();
4452 }
4453 // Makes namespace key lowercase
4454 $namespaceKey = $wgContLang->lc( $namespaceKey );
4455 // Uses main
4456 if ( $namespaceKey == '' ) {
4457 $namespaceKey = 'main';
4458 }
4459 // Changes file to image for backwards compatibility
4460 if ( $namespaceKey == 'file' ) {
4461 $namespaceKey = 'image';
4462 }
4463 return $prepend . $namespaceKey;
4464 }
4465
4466 /**
4467 * Get all extant redirects to this Title
4468 *
4469 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4470 * @return Array of Title redirects to this title
4471 */
4472 public function getRedirectsHere( $ns = null ) {
4473 $redirs = array();
4474
4475 $dbr = wfGetDB( DB_SLAVE );
4476 $where = array(
4477 'rd_namespace' => $this->getNamespace(),
4478 'rd_title' => $this->getDBkey(),
4479 'rd_from = page_id'
4480 );
4481 if ( $this->isExternal() ) {
4482 $where['rd_interwiki'] = $this->getInterwiki();
4483 } else {
4484 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4485 }
4486 if ( !is_null( $ns ) ) {
4487 $where['page_namespace'] = $ns;
4488 }
4489
4490 $res = $dbr->select(
4491 array( 'redirect', 'page' ),
4492 array( 'page_namespace', 'page_title' ),
4493 $where,
4494 __METHOD__
4495 );
4496
4497 foreach ( $res as $row ) {
4498 $redirs[] = self::newFromRow( $row );
4499 }
4500 return $redirs;
4501 }
4502
4503 /**
4504 * Check if this Title is a valid redirect target
4505 *
4506 * @return Bool
4507 */
4508 public function isValidRedirectTarget() {
4509 global $wgInvalidRedirectTargets;
4510
4511 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4512 if ( $this->isSpecial( 'Userlogout' ) ) {
4513 return false;
4514 }
4515
4516 foreach ( $wgInvalidRedirectTargets as $target ) {
4517 if ( $this->isSpecial( $target ) ) {
4518 return false;
4519 }
4520 }
4521
4522 return true;
4523 }
4524
4525 /**
4526 * Get a backlink cache object
4527 *
4528 * @return BacklinkCache
4529 */
4530 public function getBacklinkCache() {
4531 return BacklinkCache::get( $this );
4532 }
4533
4534 /**
4535 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4536 *
4537 * @return Boolean
4538 */
4539 public function canUseNoindex() {
4540 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4541
4542 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4543 ? $wgContentNamespaces
4544 : $wgExemptFromUserRobotsControl;
4545
4546 return !in_array( $this->mNamespace, $bannedNamespaces );
4547
4548 }
4549
4550 /**
4551 * Returns the raw sort key to be used for categories, with the specified
4552 * prefix. This will be fed to Collation::getSortKey() to get a
4553 * binary sortkey that can be used for actual sorting.
4554 *
4555 * @param $prefix string The prefix to be used, specified using
4556 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4557 * prefix.
4558 * @return string
4559 */
4560 public function getCategorySortkey( $prefix = '' ) {
4561 $unprefixed = $this->getText();
4562
4563 // Anything that uses this hook should only depend
4564 // on the Title object passed in, and should probably
4565 // tell the users to run updateCollations.php --force
4566 // in order to re-sort existing category relations.
4567 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4568 if ( $prefix !== '' ) {
4569 # Separate with a line feed, so the unprefixed part is only used as
4570 # a tiebreaker when two pages have the exact same prefix.
4571 # In UCA, tab is the only character that can sort above LF
4572 # so we strip both of them from the original prefix.
4573 $prefix = strtr( $prefix, "\n\t", ' ' );
4574 return "$prefix\n$unprefixed";
4575 }
4576 return $unprefixed;
4577 }
4578
4579 /**
4580 * Get the language in which the content of this page is written in
4581 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4582 * e.g. $wgLang (such as special pages, which are in the user language).
4583 *
4584 * @since 1.18
4585 * @return Language
4586 */
4587 public function getPageLanguage() {
4588 global $wgLang;
4589 if ( $this->isSpecialPage() ) {
4590 // special pages are in the user language
4591 return $wgLang;
4592 }
4593
4594 //TODO: use the LinkCache to cache this! Note that this may depend on user settings, so the cache should be only per-request.
4595 //NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
4596 $contentHandler = ContentHandler::getForTitle( $this );
4597 $pageLang = $contentHandler->getPageLanguage( $this );
4598
4599 // Hook at the end because we don't want to override the above stuff
4600 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4601 return wfGetLangObj( $pageLang );
4602 }
4603
4604 /**
4605 * Get the language in which the content of this page is written when
4606 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4607 * e.g. $wgLang (such as special pages, which are in the user language).
4608 *
4609 * @since 1.20
4610 * @return Language
4611 */
4612 public function getPageViewLanguage() {
4613 global $wgLang;
4614
4615 if ( $this->isSpecialPage() ) {
4616 // If the user chooses a variant, the content is actually
4617 // in a language whose code is the variant code.
4618 $variant = $wgLang->getPreferredVariant();
4619 if ( $wgLang->getCode() !== $variant ) {
4620 return Language::factory( $variant );
4621 }
4622
4623 return $wgLang;
4624 }
4625
4626 //NOTE: can't be cached persistently, depends on user settings
4627 //NOTE: ContentHandler::getPageViewLanguage() may need to load the content to determine the page language!
4628 $contentHandler = ContentHandler::getForTitle( $this );
4629 $pageLang = $contentHandler->getPageViewLanguage( $this );
4630 return $pageLang;
4631 }
4632 }